Sub topic 13
Partial Shuffles: Picking k Random Items
This chapter assumes you already know the in-place Fisher-Yates shuffle and why its random index has to stay inside the unshuffled part of the array. It also assumes you can read basic Python and work with simple probability.
Sometimes you only need a few items in random order, such as 5 winners from 10,000 entries or 3 cards from a deck. You could shuffle the entire list and keep the first k items. That works, but most of the swaps would be wasted, because a shuffle chooses every position and you only use k of them.
Stopping the Shuffle Early
Fisher-Yates chooses positions one at a time, and every chosen position is final. The forward version of the loop fills position 0 first, then position 1, and so on. On step i it picks a uniformly random element from the part not yet chosen, which is indices i through n − 1, and swaps it into position i. After k steps, the first k positions hold a uniformly random ordered sample, and you can stop there.
import random
def sample_k(items, k):
n = len(items)
for i in range(k):
j = random.randint(i, n - 1) # choose from the unchosen region only
items[i], items[j] = items[j], items[i]
return items[:k]
deck = list(range(52))
print(sample_k(deck, 5))The loop does k swaps where a full shuffle would do n − 1. It needs no extra memory beyond the k-element result slice.
Why the Sample Is Fair
Step 0 has n equally likely choices. Step 1 has n − 1, and so on, down to n − k + 1 choices at the last step. Every sequence of choices produces a different ordered sample, so each ordered sample of k distinct items has probability:
1 / (n × (n − 1) × … × (n − k + 1)) = (n − k)! / n!
This is the same uniformity argument as the full-shuffle proof, cut off after k factors. When k = n, it gives 1/n!.
Common Errors
| Mistake | Effect |
|---|---|
| `randint(0, n - 1)` instead of `randint(i, n - 1)` | Already-chosen items can be swapped back out, which brings back the naive shuffle's bias |
| Running the backward loop and returning `items[:k]` | The backward loop finalizes the end of the list first, so return `items[n-k:]` instead |
| Forgetting the input is modified | The caller's list is left partly shuffled |
| Using `randrange(i + 1, n)` | The item at position i can never stay where it is, so the sample is biased |
Use the Library When You Can
Python's random.sample(population, k) returns k distinct items in random order and leaves the original unchanged. It chooses an internal strategy based on the sizes of n and k. Write your own partial shuffle when you need it in place, need it in another language, or want to control the random source, for example by passing in random.SystemRandom.
Exercise
You call sample_k on a list of 10 distinct items with k = 3. What is the probability of getting exactly the ordered result [7, 2, 9]? What about getting the items {2, 7, 9} in any order?
Show answer
The ordered result has probability 1/(10 × 9 × 8) = 1/720. The three items can appear in 3! = 6 orders, so getting the set {2, 7, 9} in any order has probability 6/720 = 1/120, which is 1 divided by C(10, 3).
Exercise
A colleague writes the loop as for i in range(k): j = random.randint(0, n - 1). Explain in one sentence why this is wrong.
Show answer
It can pick j < i, which swaps an already-chosen item back into the unchosen region, so the choices are no longer uniform over the remaining items and the sample becomes biased.