جواب «A Random Poet» چالش 4 از جلسهی 34
سؤال
دمای ۱: عدد شانس (seed) با input میآید. شش بار: اگر کلمهی آخر در table نبود break کن، وگرنه random.choice(table[word]) را به line اضافه کن. با عدد شانس 1 خروجی یک جمله است که از the شروع میشود. هر عدد شانس جملهی دیگری میدهد، ولی هر عدد همیشه همان جمله را.
راهنما
داخل حلقه، زیر word = line[-1]: if word not in table: break و line.append(random.choice(table[word])).
یک جواب درست
POEMS = [
"the cat sat on the mat",
"the cat ran to the sun",
"the dog sat in the sun",
"the sun is warm and bright",
"the moon is round and white",
"a bird can sing in the tree",
]
table = {}
for line in POEMS:
words = line.split()
for i in range(len(words) - 1):
if words[i] not in table:
table[words[i]] = []
table[words[i]].append(words[i + 1])
import random
random.seed(int(input()))
line = ["the"]
for i in range(6):
word = line[-1]
if word not in table:
break
line.append(random.choice(table[word]))
print(" ".join(line))
اول خودت امتحان کن؛ جوابهای دیگر هم قبول است. برگرد و خودت حلش کن