Create a gist now

Instantly share code, notes, and snippets.

anonymous /shuffletest.py
Created May 28, 2012

What would you like to do?
Array shuffle test examples
import random
def testShuffle(shuffle, trials):
baseList = [1, 2, 3, 4]
counts = {}
for i in range(trials):
shuffleList = shuffle(baseList[:])
key = str(shuffleList)
if not (key in counts):
counts[key] = 1
else:
counts[key] += 1
sortedKeys = counts.keys()
sortedKeys.sort()
for key in sortedKeys:
print key, "\t", round(counts[key] / float(trials), 4)
def fisher_yates(shuffleList):
for i in range(len(shuffleList)):
index = random.randint(0, i)
item = shuffleList[i]
shuffleList[i] = shuffleList[index]
shuffleList[index] = item
return shuffleList
def naive(shuffleList):
listLength = len(shuffleList)
for i in range(listLength):
index = random.randint(0, listLength-1)
item = shuffleList[i]
shuffleList[i] = shuffleList[index]
shuffleList[index] = item
return shuffleList
def terrible(shuffleList):
for i in range(len(shuffleList)):
index = random.randint(0, 3)
item = shuffleList[index]
shuffleList.pop(index)
shuffleList.append(item)
return shuffleList
print "Fisher-Yates"
testShuffle(fisher_yates, 500000)
print "Naive"
testShuffle(naive, 500000)
print "Terrible"
testShuffle(terrible, 500000)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment