Split a text into overlapping chunks

Before indexing, long texts are split into chunks that share a few words with their neighbours. Split one.

What to build

A program that splits a text into chunks of at most N words, where neighbouring chunks share O words.

Requirements

  • The first chunk starts at the first word; each next chunk starts N − O words after the previous start.
  • Each chunk has N words, or fewer if the text ends; stop after the first chunk that includes the last word.
  • Print each chunk as chunk I: WORDS, counting from 1.

Input

Line 1: N and O. Line 2: the text.

Output

One line per chunk.

Constraints

1 ≤ N ≤ 1000; 0 ≤ O < N; 1 to 100,000 words.

Example

Input:

4 1
a b c d e f g h i j

Output:

chunk 1: a b c d
chunk 2: d e f g
chunk 3: g h i j

Why it works

Stepping by N − O makes each chunk repeat the last O words of the previous one, so text near a boundary appears complete in at least one chunk.

Examples

Example 1 · Input
4 1
a b c d e f g h i j
Expected output
chunk 1: a b c d
chunk 2: d e f g
chunk 3: g h i j
Example 2 · Input
5 0
one two three
Expected output
chunk 1: one two three

Prompts inside input() are ignored when checking, so input("n: ") is fine.

Hints

Hint 1

Chunks start at word 0, N − O, 2(N − O), ...

Hint 2

Stop after the chunk that reaches the last word.

Solution

Show one correct solution (try it yourself first)
n, o = map(int, input().split())
words = input().split()
start, number = 0, 1
while True:
    chunk = words[start : start + n]
    print(f"chunk {number}:", *chunk)
    if start + n >= len(words):
        break
    start += n - o
    number += 1

Lesson: Semantic search →