Created
April 10, 2018 19:16
-
-
Save Beefster09/b6a10b1856e1df11021802e48b0a26a7 to your computer and use it in GitHub Desktop.
Riffle Shuffling
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 _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