Skip to content

Instantly share code, notes, and snippets.

@earonesty
Created September 27, 2019 19:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save earonesty/cfaae2a78dce6aff3f884ff5c7381179 to your computer and use it in GitHub Desktop.
Save earonesty/cfaae2a78dce6aff3f884ff5c7381179 to your computer and use it in GitHub Desktop.
randomize a generator stream within a fixed window
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