Created
July 22, 2008 22:24
-
-
Save harryf/1333 to your computer and use it in GitHub Desktop.
Card 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
#!/usr/bin/env python | |
# -*- coding: utf-8 -*- | |
from random import randrange | |
def fisher_yates_shuffle(unshuffled, shuffled): | |
""" | |
http://en.wikipedia.org/wiki/Fisher-Yates_shuffle#The_modern_algorithm | |
...but using recursion instead of counters | |
""" | |
if not unshuffled: return shuffled | |
randi = randrange(0, len(unshuffled)) | |
# the challenge would be to support tuples... | |
unshuffled[0], unshuffled[randi] = unshuffled[randi], unshuffled[0] | |
return fisher_yates_shuffle(unshuffled[1:], shuffled + [unshuffled[0]]) | |
def sort_shuffle(cards): | |
""" | |
http://en.wikipedia.org/wiki/Fisher-Yates_shuffle#Comparison_with_other_shuffling_algorithms | |
Same again but sort use a random list of weights... | |
(returns a tuple not a list) | |
""" | |
weights = range(len(cards)) | |
random_weights = [] | |
while weights: | |
random_weights.append(weights.pop(randrange(0, len(weights)))) | |
return zip(*sorted(zip(random_weights, cards)))[1] | |
if __name__ == '__main__': | |
cards = range(52) | |
print fisher_yates_shuffle(cards, []) | |
print sort_shuffle(cards) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment