Sub topic 11
Testing a Shuffle with Frequency Counts
This chapter assumes you know the fisher_yates and naive_shuffle functions from earlier chapters, Python's collections.Counter, and the idea that a fair shuffle gives each of the n! permutations probability 1/n!.
A proof tells you the algorithm is correct. It does not tell you whether your code is correct. A swapped bound or a wrong random range can quietly bring bias back. Counting permutation frequencies is a cheap way to catch those mistakes.
The idea: count, compare, measure
Shuffle a small list many times and record which permutation comes out each time. With n = 3 there are 6 permutations. In 60,000 trials, a fair shuffle should produce each one about 10,000 times. A biased shuffle produces some permutations noticeably more often than others.
Looking at the counts by eye works for gross bias. For subtle bias you need a number, and the chi-square statistic is the standard choice:
χ² = Σ (observed − expected)² / expected
The sum runs over all n! permutations. A small χ² means the counts sit close to the expected value.
A runnable test
import random
from collections import Counter
from itertools import permutations
def fisher_yates(items):
for i in range(len(items) - 1, 0, -1):
j = random.randint(0, i)
items[i], items[j] = items[j], items[i]
return items
def naive_shuffle(items):
n = len(items)
for i in range(n):
j = random.randint(0, n - 1)
items[i], items[j] = items[j], items[i]
return items
def chi_square(shuffle, n=3, trials=60000):
counts = Counter(tuple(shuffle(list(range(n)))) for _ in range(trials))
perms = list(permutations(range(n)))
expected = trials / len(perms)
# counts[p] is 0 for a permutation that never appeared, so missing ones still count
return sum((counts[p] - expected) ** 2 / expected for p in perms)
print("Fisher-Yates:", round(chi_square(fisher_yates), 2))
print("Naive: ", round(chi_square(naive_shuffle), 2))Because the loop runs over every permutation from itertools.permutations, a permutation that never occurs still adds its full expected count to χ². That matters: a shuffle that never produces some ordering, as Sattolo's algorithm does, gets a very large score.
Reading the result
With n! − 1 = 5 degrees of freedom, the critical values are:
| Significance level | Critical χ² (5 degrees of freedom) |
|---|---|
| 0.05 | 11.07 |
| 0.01 | 15.09 |
| 0.001 | 20.52 |
Fisher-Yates usually scores in single digits. The naive shuffle produces counts near 8,889 and 11,111 (in the ratio 4:5 out of 27), which gives a χ² in the hundreds.
Common mistakes
- Too few trials. Aim for at least a few hundred expected hits per permutation. With 600 trials, small biases disappear into the noise.
- Testing a large n. For 10 items, 10! = 3,628,800 permutations need tens of millions of trials. Test full permutations at n = 3 or 4. For larger lists, check a weaker condition: each element should land in each position with probability 1/n.
- Shuffling the same list object repeatedly. That is fine for a fair shuffle, but it hides bugs that depend on the starting order. Start each trial from a fresh
list(range(n)). - Treating a pass as proof. A pass means the test found no bias it could detect. It does not show that no bias exists.
Exercise
You change the inner line of fisheryates to j = random.randrange(i), which turns it into Sattolo's algorithm, and run chisquare with n = 3 and 60,000 trials. Roughly what χ² do you expect, and why?
Show answer
Sattolo's algorithm produces only the 2 single-cycle permutations of 3 items, each about 30,000 times, and the other 4 never appear. Each of the 2 produced permutations contributes (30000 − 10000)² / 10000 = 40,000, and each of the 4 missing ones contributes (0 − 10000)² / 10000 = 10,000. The total is about 120,000, far above any critical value.
Exercise
A position-frequency test on a 52-card shuffle passes: every card lands in every position about equally often. Does this prove the shuffle is uniform over all 52! orderings?
Show answer
No. Position frequencies only check one-item marginals. A shuffle can place each card uniformly in each position and still favor some full orderings. For example, a random rotation of the deck passes this test but reaches only 52 of the 52! permutations.