جواب «Step 2: One Line» چالش 2 از جلسهی 36
سؤال
قدم دوم: تابع make_line(start, followers, max_words) را کامل کن: از start شروع کن، هر بار با random.choice کلمهی بعدی را بردار؛ اگر <end> بود یا به max_words رسیدی، تمام. خط را با فاصله بچسبان و برگردان (<end> در خط نباشد). برنامه با random.seed(1) یک خط میسازد؛ باید بدون خطا تمام شود و خط با the شروع شود و بیشتر از ۸ کلمه نباشد.
راهنما
while len(words) < max_words: nxt = random.choice(followers[words[-1]]); if nxt == "<end>": break; words.append(nxt).
یک جواب درست
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)
random.seed(1)
line = make_line("the", followers, 8)
print(line)
print(len(line.split()) <= 8 and "<end>" not in line)
اول خودت امتحان کن؛ جوابهای دیگر هم قبول است. برگرد و خودت حلش کن