Array shuffle test examples
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 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