Exercise: Sliding windows

Many interview problems look at every run of k consecutive items: moving averages, "max sum of k in a row", spotting repeats in a stream.

Exercise: write windows, a generator that yields each window of k consecutive items as a tuple.

list(windows([1, 2, 3, 4], 2))  # [(1, 2), (2, 3), (3, 4)]
  • It must work on any iterable, including a generator you can only read once, so no len() and no slicing.
  • It must be lazy: on an endless input, it still yields windows one by one.
  • Fewer than k items means no windows at all.
  • k less than 1 raises ValueError.

Hint: collections.deque(maxlen=k) is a list that drops its oldest item when you append past k. Once it is full, yield tuple(window) after each append.

(Python 3.12 added itertools.batched, and 3.10 added pairwise for k = 2. Writing it yourself is the point here.)

Press Check to run the tests.