Step 2: One Line چالش 2 از جلسهی 36، متوسط
قدم دوم: تابع make_line(start, followers, max_words) را کامل کن: از start شروع کن، هر بار با random.choice کلمهی بعدی را بردار؛ اگر <end> بود یا به max_words رسیدی، تمام. خط را با فاصله بچسبان و برگردان (<end> در خط نباشد). برنامه با random.seed(1) یک خط میسازد؛ باید بدون خطا تمام شود و خط با the شروع شود و بیشتر از ۸ کلمه نباشد.
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]
# loop until <end> or max_words
return " ".join(words)
followers = build(POEM)
random.seed(1)
line = make_line("the", followers, 8)
print(line)
print(len(line.split()) <= 8 and "<end>" not in line)
راهنما و جواب این چالش · برگشت به درس جلسهی 36: پروژه: شاعر کوچک · چالش بعدی: Step 3: A Whole Poem
بیشتر بخوان: تابع در پایتون: آموزش def، پارامتر و return با مثال