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

جواب «Generate Text» چالش 4 از جلسه‌ی 35

سؤال

تابع generate(start, length) را کامل کن: از start شروع کن و length - 1 بار کلمه‌ی بعدی را با random.choice از جدول انتخاب کن؛ اگر کلمه در جدول نبود، متوقف شو. برنامه با random.seed(7) تولید می‌کند. برنامه باید بدون خطا تمام شود و یک جمله‌ی ۸ کلمه‌ای چاپ کند که با the شروع می‌شود.

راهنما

for i in range(length - 1): if word not in followers: break; word = random.choice(followers[word]); result.append(word).

یک جواب درست

import random

followers = {"the": ["cat", "mat", "cat", "fish"], "cat": ["sat", "ate"], "sat": ["on"], "on": ["the"], "mat": ["the"], "ate": ["the"]}


def generate(start, length):
    word = start
    result = [word]
    for i in range(length - 1):
        if word not in followers:
            break
        word = random.choice(followers[word])
        result.append(word)
    return " ".join(result)


random.seed(7)
print(generate("the", 8))

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