Step 4: Poet with Temperature چالش 4 از جلسهی 36، سخت
قدم آخر: make_line را با پارامتر temperature بازنویسی کن: اگر random.random() < temperature کلمهی بعدی تصادفی از جدول، وگرنه پرتکرارترین (با Counter). برنامه با random.seed(5) یک خط با دمای ۰ و یک خط با دمای ۱ میسازد. خط اول باید دقیقاً the little cat sat on the little باشد (حریصانه و تکراری!)؛ بعد از آن True چاپ میشود اگر هر دو خط حداکثر ۷ کلمه داشته باشند.
import random
from collections import Counter
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, temperature):
words = [start]
while len(words) < max_words:
options = followers[words[-1]]
# pick nxt: random if random.random() < temperature, else most common
nxt = options[0]
if nxt == "<end>":
break
words.append(nxt)
return " ".join(words)
followers = build(POEM)
random.seed(5)
cold = make_line("the", followers, 7, 0)
hot = make_line("the", followers, 7, 1)
print(cold)
print(hot)
print(len(cold.split()) <= 7 and len(hot.split()) <= 7)
راهنما و جواب این چالش · برگشت به درس جلسهی 36: پروژه: شاعر کوچک
بیشتر بخوان: تابع در پایتون: آموزش def، پارامتر و return با مثال