easy +8 pts

Window Iterator

Create a generator that yields sliding windows of a sequence.

Implement a generator function named `windowed` that accepts two arguments: `iterable` (any iterable) and `size` (a positive integer). It should yield lists of length `size` that represent consecutive overlapping windows over the sequence of elements in `iterable`. The first window starts at the first element, the second starts at the second element, and so on. If the total number of elements in the iterable is less than `size`, the generator yields nothing. The iterable may be any iterable (e.g., list, string, tuple, generator). Your generator must not consume the entire iterable into memory unnecessarily (it should work with infinite or long iterables). However, for testing purposes, the inputs will be finite. The function signature is: ```python def windowed(iterable, size): ... ```

Constraints

`size` is a positive integer. The iterable can be strings, lists, tuples, or generators. The generated windows are lists of length `size`. The function must be a generator function (must contain `yield`). Complexity: O(n) time, O(size) memory.

Example

>>> list(windowed([1, 2, 3, 4], 2))
[[1, 2], [2, 3], [3, 4]]
>>> list(windowed('abcdef', 3))
[['a', 'b', 'c'], ['b', 'c', 'd'], ['c', 'd', 'e'], ['d', 'e', 'f']]
>>> list(windowed([1, 2, 3], 5))
[]
8 points ~12 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

Use a collections.deque to maintain a sliding buffer, or use tee to create multiple independent iterators and zip them.
If using a simple loop with a list as a buffer, be careful to only yield when the buffer reaches the required size.
You can create `size` iterators that are offset and then zip them together, but be mindful of the first few iterations that are incomplete.
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.