جواب «Three Temperatures» چالش 5 از جلسهی 34
سؤال
تابع next_word(word, temp) را کامل کن: اگر temp == 0 بود most_common(word)، اگر temp == 1 بود random.choice(table[word]) و برای دمای بیشتر یک کلمهی کاملاً تصادفی از همهی کلمهها: random.choice(VOCAB). برنامه با هر سه دما یک جمله میسازد. خط اول:temp 0 : the sun is warm and bright
دو خط دیگر را ببین: کدام بیمعنیتر است؟
راهنما
سه شاخه: if temp == 0: return most_common(word)، if temp == 1: return random.choice(table[word])، و آخر return random.choice(VOCAB).
یک جواب درست
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
VOCAB = sorted(table)
def most_common(word):
best = table[word][0]
for w in table[word]:
if table[word].count(w) > table[word].count(best):
best = w
return best
def next_word(word, temp):
if temp == 0:
return most_common(word)
if temp == 1:
return random.choice(table[word])
return random.choice(VOCAB)
for temp in [0, 1, 2]:
random.seed(4)
line = ["the"]
for i in range(5):
if line[-1] not in table:
break
line.append(next_word(line[-1], temp))
print("temp", temp, ":", " ".join(line))
اول خودت امتحان کن؛ جوابهای دیگر هم قبول است. برگرد و خودت حلش کن