Last active
November 14, 2023 21:58
-
-
Save therealzanfar/817a73a77a49b77226475ba9541c52c0 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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