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

جواب «Step 1: Table with <end>» چالش 1 از جلسه‌ی 36

سؤال

قدم اول: تابع build(text) را کامل کن که برای هر خط، <end> را به آخر کلمه‌ها اضافه کند و جدول بعدی‌ها را بسازد. برنامه followers["mat"]، followers["the"][:3] و تعداد <end> در کل جدول را چاپ می‌کند: ['<end>']، ['little', 'mat', 'little'] و 6.

راهنما

for i in range(len(words) - 1): followers.setdefault(words[i], []).append(words[i + 1]).

یک جواب درست

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


followers = build(POEM)
print(followers["mat"])
print(followers["the"][:3])
print(sum(lst.count("<end>") for lst in followers.values()))

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