Chunk Text into Overlapping Windows
Problem Statement
Split a long token stream into fixed-size chunks with a fixed overlap, the standard preprocessing for populating a vector memory.
Background
Given n tokens, a chunk size size, and an overlap, chunks start at *0, size-overlap, 2(size-overlap), ...**. Each chunk spans [start, min(start+size, n)). Generation stops once a chunk reaches the end. The step size - overlap must be positive.
Your Task
Implement:
def chunk_ranges(n, size, overlap):
Return a list of (start, end) tuples (end exclusive) covering the stream, with the given overlap. Stop after the chunk that reaches n.
Input Format
- n (int) total tokens, size (int), overlap (int) with 0 <= overlap < size.
Output Format
- A list of (start, end) int tuples.
Sample
print(chunk_ranges(10, 4, 1))
Output:
[(0, 4), (3, 7), (6, 10)]
Example
print(chunk_ranges(10, 4, 1))
[(0, 4), (3, 7), (6, 10)]
- Compute the stride between chunk starts using the formula , which yields ; this determines how far the window shifts after each chunk.
- Initialize the first chunk at index 0; its end is calculated as , producing the range since it has not yet reached the total length .
- Advance the start position by the stride to ; the new end is , creating the overlapping range where the overlap of 1 token is shared with the previous chunk.
- Advance the start position again by the stride to ; the new end is , creating the range .
- Since the end index equals the total token count , the generation stops, and the final output is
[(0, 4), (3, 7), (6, 10)].
Constraints
0 <= overlap < size,size >= 1,n >= 0.- Step is
size - overlap; each chunk is[start, min(start+size, n)). - Stop once a chunk's end reaches
n; ifn == 0return[].