Skip to content

Instantly share code, notes, and snippets.

@Beefster09
Created April 10, 2018 19:16
Show Gist options
  • Save Beefster09/b6a10b1856e1df11021802e48b0a26a7 to your computer and use it in GitHub Desktop.
Save Beefster09/b6a10b1856e1df11021802e48b0a26a7 to your computer and use it in GitHub Desktop.
Riffle Shuffling
import random
def _perfect_riffle():
while True:
yield 0
yield 1
perfect_riffle = _perfect_riffle().__next__
def riffle(left, right, *, rand=random.random):
result = []
ileft, cleft = iter(left), len(left)
iright, cright = iter(right), len(right)
while cleft + cright:
if rand() < cleft / (cleft + cright):
result.append(next(ileft))
cleft -= 1
else:
result.append(next(iright))
cright -= 1
return result
def riffle_shuffle(seq, n=6, *, rand=random.random):
half = len(seq) // 2
for i in range(n):
seq = riffle(seq[:half], seq[half:], rand=rand)
return seq
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment