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

جواب «Chunks That Overlap» چالش 3 از جلسه‌ی 71

سؤال

تابع chunk_overlap(text, size, overlap) را بنویس: قدم = size - overlap؛ از هر شروع یک تکه‌ی size کلمه‌ای بساز، و وقتی تکه به آخر متن رسید (start + size >= len(words)) دیگر ادامه نده. برنامه برای هر تکه، کلمه‌ی شروع و پایان و سه کلمه‌ی اولش را چاپ می‌کند. خروجی:
words 0-19: The water cycle ...
words 15-34: lakes. The warm ...
words 30-49: the sky the ...
words 45-59: in a cloud ...

راهنما

step = size - overlap؛ for start in range(0, len(words), step): → part = words[start:start + size]، chunks.append((start, start + len(part) - 1, part)) و if start + size >= len(words): break.

یک جواب درست

NOTES = ("The water cycle moves water around the Earth. The sun heats water in seas and lakes. "
         "The warm water turns into vapour and rises. This is called evaporation. High in the sky "
         "the vapour cools and forms clouds. This is called condensation. When the drops in a cloud "
         "get heavy, they fall as rain or snow. This is called precipitation.")


def chunk_overlap(text, size, overlap):
    words = text.split()
    chunks = []          # a list of (start, end, chunk_words)
    step = size - overlap
    for start in range(0, len(words), step):
        part = words[start:start + size]
        chunks.append((start, start + len(part) - 1, part))
        if start + size >= len(words):
            break
    return chunks


for start, end, part in chunk_overlap(NOTES, 20, 5):
    print(f"words {start}-{end}: {' '.join(part[:3])} ...")

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