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

Step 3: A Whole Poem چالش 3 از جلسه‌ی 36، متوسط

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

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):
    pass


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

راهنما و جواب این چالش · برگشت به درس جلسه‌ی 36: پروژه: شاعر کوچک · چالش بعدی: Step 4: Poet with Temperature

بیشتر بخوان: تابع در پایتون: آموزش def، پارامتر و return با مثال