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

جواب «The Most Common Next Word» چالش 3 از جلسه‌ی 34

سؤال

جدول از شش شعر POEMS ساخته شده. تابع most_common(word) را بنویس: از best = table[word][0] شروع کن و هر کلمه‌ای از table[word] که countاش بیشتر بود، best شود. برنامه با دمای صفر از the یک جمله‌ی شش‌کلمه‌ای می‌سازد:
the sun is warm and bright

راهنما

for w in table[word]: if table[word].count(w) > table[word].count(best): best = w.

یک جواب درست

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])

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

line = ["the"]
for i in range(5):
    line.append(most_common(line[-1]))
print(" ".join(line))

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