بتل کد Battle Codeدارد باز می‌شود…

جواب «Step 3: A Whole Poem» چالش 3 از جلسه‌ی 36

سؤال

قدم سوم: تابع make_poem(lines, followers) بنویس که lines خط بسازد و هر خط را با یک کلمه‌ی شروع تصادفی از starts (کلمه‌های اول خط‌های اصلی) آغاز کند؛ خط‌ها را با \n به هم بچسبان. برنامه با random.seed(2) یک شعر ۴ خطی چاپ می‌کند و بعد 4 (تعداد خط‌ها). باید بدون خطا تمام شود.

راهنما

result = []؛ for i in range(lines): result.append(make_line(random.choice(starts), followers, 8))؛ return "\n".join(result).

یک جواب درست

import random

POEM = '''
the little cat sat on the mat
the little dog ran to the park
the sun is up the sky is blue
the moon is up the night is dark
the cat and dog play in the sun
the little bird sings in the tree
'''


def build(text):
    followers = {}
    for line in text.strip().splitlines():
        words = line.split() + ["<end>"]
        for i in range(len(words) - 1):
            followers.setdefault(words[i], []).append(words[i + 1])
    return followers


def make_line(start, followers, max_words):
    words = [start]
    while len(words) < max_words:
        nxt = random.choice(followers[words[-1]])
        if nxt == "<end>":
            break
        words.append(nxt)
    return " ".join(words)


followers = build(POEM)
starts = [line.split()[0] for line in POEM.strip().splitlines()]


def make_poem(lines, followers):
    result = []
    for i in range(lines):
        result.append(make_line(random.choice(starts), followers, 8))
    return "\n".join(result)


random.seed(2)
poem = make_poem(4, followers)
print(poem)
print(len(poem.split("\n")))

اول خودت امتحان کن؛ جواب‌های دیگر هم قبول است. برگرد و خودت حلش کن