Windows over a list

Produce every run of k neighbouring items.

What to build

A generator that yields one window at a time.

Requirements

  • Complete windows(items, k) so that it yields each run of k neighbouring items, as a list, from left to right.
  • Leave the rest of the program as it is. It prints each window and how many there were.

Input

The first line has n and k. The second line has n whole numbers.

Output

One line per window, then windows C.

Constraints

n and k are from 1 to 100. k may be larger than n.

Example

Input:

4 2
1 2 3 4

Output:

1 2
2 3
3 4
windows 3

Why it works

The generator hands out one slice at a time, so the caller can stop early. When k is too large the range is empty and no window is produced.

Examples

Example 1 · Input
4 2
1 2 3 4
Expected output
1 2
2 3
3 4
windows 3
Example 2 · Input
3 3
5 6 7
Expected output
5 6 7
windows 1

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

Hints

Hint 1

There are len(items) - k + 1 windows.

Hint 2

Yield a slice for each starting position.

Hint 3

If k is larger than the list, the loop simply does not run.

Solution

Show one correct solution (try it yourself first)
def windows(items, k):
    for start in range(len(items) - k + 1):
        yield items[start:start + k]

n, k = [int(x) for x in input().split()]
nums = [int(x) for x in input().split()]
count = 0
for w in windows(nums, k):
    print(" ".join(str(x) for x in w))
    count += 1
print("windows", count)

Lesson: Generators →