بتل کد Battle Codeدارد باز می‌شود…

جواب «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 چاپ می‌شود اگر هر دو خط حداکثر ۷ کلمه داشته باشند.

راهنما

if random.random() < temperature: nxt = random.choice(options) و در غیر این صورت nxt = Counter(options).most_common(1)[0][0].

یک جواب درست

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]]
        if random.random() < temperature:
            nxt = random.choice(options)
        else:
            nxt = Counter(options).most_common(1)[0][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)

اول خودت امتحان کن؛ جواب‌های دیگر هم قبول است. برگرد و خودت حلش کن