Created
September 27, 2019 19:48
-
-
Save earonesty/cfaae2a78dce6aff3f884ff5c7381179 to your computer and use it in GitHub Desktop.
randomize a generator stream within a fixed window
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
import random | |
def scramble(gen, buffer_size): | |
buf = [] | |
i = iter(gen) | |
while True: | |
try: | |
e = next(i) | |
buf.append(e) | |
if len(buf) >= buffer_size: | |
choice = random.randint(0, len(buf)-1) | |
buf[-1], buf[choice] = buf[choice], buf[-1] | |
yield buf.pop() | |
except StopIteration: | |
random.shuffle(buf) | |
yield from buf | |
return | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment