Skip to content

Instantly share code, notes, and snippets.

@therealzanfar
Last active November 14, 2023 21:58
Show Gist options
  • Save therealzanfar/817a73a77a49b77226475ba9541c52c0 to your computer and use it in GitHub Desktop.
Save therealzanfar/817a73a77a49b77226475ba9541c52c0 to your computer and use it in GitHub Desktop.
from collections import deque
from typing import TypeVar, Iterable, Iterator
T = TypeVar("T")
def window(i: Iterable[T], size: int = 2) -> Iterator[tuple[T, ...]]:
"""Yield a sliding window of items from an iterator."""
i: Iterable[T] = iter(i)
w: deque[T] = deque()
qsize = max(1, size)
for _ in range(qsize):
try:
w.append(next(i))
except StopIteration:
yield tuple(w)
return
yield tuple(w)
for e in i:
w.append(e)
w.popleft()
yield tuple(w)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment