Last active
September 9, 2020 23:46
-
-
Save dirkgr/23958653430f5b30bce5f3317ccf2a97 to your computer and use it in GitHub Desktop.
Shuffle the output of an iterator
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 typing import * | |
import random | |
def shuffle_iterable(i: Iterable, pool_size: int = 1024) -> Iterable: | |
import random | |
i = iter(i) | |
pool = [] | |
# fill up the pool | |
for item in i: | |
pool.append(item) | |
if len(pool) >= pool_size: | |
break | |
# play in it | |
while len(pool) > 0: | |
index = random.randrange(len(pool)) | |
yield pool[index] | |
try: | |
pool[index] = next(i) | |
except StopIteration: | |
del pool[index] | |
break | |
# drain it | |
random.shuffle(pool) | |
yield from pool |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment