This file contains 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
class _NoPadding: pass | |
_Chunk_T = TypeVar("_Chunk_T") | |
def _windowed(iterable: Iterable[_Chunk_T], size: int, step: int = 1, padding: _NoPadding|Any = _NoPadding()) -> Iterable[Iterable[_Chunk_T|None]]: | |
it = iter(iterable) | |
chunk: List[_Chunk_T|Any] = [] | |
while True: | |
# Pop step items from the buffer | |
if chunk: | |
for _ in range(step): | |
chunk.pop(0) | |
# Fill the buffer | |
for _ in range(size - len(chunk)): | |
try: | |
chunk.append(next(it)) | |
except StopIteration: | |
# We've hit the end, add padding | |
if not isinstance(padding, _NoPadding): | |
if len(chunk) != size: | |
for _ in range(size - len(chunk)): | |
chunk.append(padding) | |
yield chunk | |
return | |
# Yield the buffer | |
yield chunk | |
for chunk in _windowed([1,2,3,4,5,6,7], 4, 2, padding=0): | |
print(list(chunk)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment