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
دو خط دیگر را ببین: کدام بیمعنیتر است؟
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):
return most_common(word)
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))
راهنما و جواب این چالش · برگشت به درس جلسهی 34: کلمهی بعدی را حدس بزن · چالش بعدی: Real or Made Up?
بیشتر بخوان: تابع در پایتون: آموزش def، پارامتر و return با مثال