Created
April 4, 2023 14:33
-
-
Save rkhullar/637e0641faae5e74624073210f5853cc to your computer and use it in GitHub Desktop.
python iter batch v1
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
from typing import Iterator, List, TypeVar | |
T = TypeVar('T') | |
def iter_batch(sequence: Iterator[T], size: int) -> Iterator[List[T]]: | |
count, buffer = 0, [None] * size | |
for item in sequence: | |
idx = count % size | |
buffer[idx] = item | |
if idx + 1 == size: | |
yield buffer | |
count += 1 | |
remaining = count % size | |
if remaining > 0: | |
yield buffer[: remaining] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment