Sub topic 4
Warm-Up: Keeping One Random Item
This chapter assumes you can read basic Python, know what independent random events are, and can multiply probabilities. Before we sample k items, we solve a smaller problem. We want to pick one item uniformly at random from a stream, in a single pass, without knowing how long the stream is. Uniformly means that if the stream ends after n items, each item must be the final choice with probability exactly 1/n.
The idea: replace with probability 1/i
We keep a single variable, chosen. When the i-th item arrives (counting from 1), we replace chosen with it with probability 1/i. Otherwise we keep what we had.
- Item 1 is always taken, since 1/1 = 1.
- Item 2 replaces it half the time.
- Item 3 replaces the current choice one third of the time, and so on.
The probability of replacement goes down as the stream grows. Each new item has to compete with everything that came before it, so its chance of being taken has to shrink.
import random
def sample_one(stream, rng=random):
chosen = None
for i, item in enumerate(stream, start=1):
# Replace the current choice with probability 1/i
if rng.randrange(i) == 0:
chosen = item
return chosen
if __name__ == "__main__":
rng = random.Random(42)
print(sample_one(["a", "b", "c", "d", "e"], rng))
print(sample_one(iter(range(1_000_000)), rng)) # works on a one-shot iteratorrng.randrange(i) returns an integer from 0 to i − 1, each with probability 1/i. Testing for == 0 therefore fires with probability exactly 1/i. The function holds one item and one counter at all times, no matter how long the stream is.
Why each item ends up with probability 1/n
For item i to be the final answer, two things must happen. It must be taken when it arrives, which has probability 1/i. Then every later item j must fail to replace it, which has probability 1 − 1/j = (j − 1)/j for each j. These draws are independent, so we multiply:
P(item i is final) = (1/i) · (i/(i+1)) · ((i+1)/(i+2)) · … · ((n−1)/n)
Each numerator cancels the denominator before it, and the product reduces to 1/n. The value of i drops out completely, so every position gets the same chance. A later chapter extends this argument to a reservoir of k items using induction.
Here is a worked example with n = 4:
| Item | Taken on arrival | Survives later items | Final probability |
|---|---|---|---|
| 1 | 1 | 1/2 · 2/3 · 3/4 | 1/4 |
| 2 | 1/2 | 2/3 · 3/4 | 1/4 |
| 3 | 1/3 | 3/4 | 1/4 |
| 4 | 1/4 | 1 (no later items) | 1/4 |
The invariant is worth remembering. After the algorithm has processed i items, chosen is a uniform pick from those i items. This holds at every step, so you can stop the stream at any point and the answer is already correct.
Common errors
- Empty streams. The function returns
None. IfNonecan be a real item in your stream, use a sentinel object or raise an exception instead. - Using
random.random() < 1/i. This is close to correct, but floating-point division adds a tiny bias when i is large. Integer draws avoid that bias. - Reusing one global RNG in tests. Pass a seeded
random.Randomso your results can be reproduced.
Exercise
A colleague writes if rng.random() < 1/2: chosen = item for every item after the first, using a fixed probability of one half. With a stream of 3 items, what is the probability that item 1 is the final choice?
Show answer
Item 1 is taken, then it must survive two replacement attempts that each succeed with probability 1/2. That gives (1/2)(1/2) = 1/4. Item 2 has probability (1/2)(1/2) = 1/4, and item 3 has 1/2. The result is not uniform, because the replacement probability has to shrink as 1/i.
Exercise
Change sample_one so it also returns how many times chosen was replaced. What is the expected number of replacements for a stream of n items?
Show answer
Add a counter that increments inside the if-block. The expected count is the sum of 1/i for i from 1 to n, which is the harmonic number H_n ≈ ln n + 0.577. For n = 1,000,000 that is about 14.4 replacements.