Sub topic 4
Warm-Up: Keeping One Random Item
Before keeping a sample of k items from a stream, it helps to solve the smallest version of the problem: keep one item, chosen uniformly at random, from a stream you can read only once and whose length you don't know. The same idea, scaled up, becomes Algorithm R in the next chapter.
This chapter assumes you can read Python generators and iterators, multiply conditional probabilities, and read Big-O notation. Earlier chapters defined the streaming model (single pass, unknown length, bounded memory) and showed why naive approaches fail, so neither is repeated here.
The Problem in One Sentence
Read items x₁, x₂, …, xₙ one at a time. Store only a constant amount of state. When the stream ends, return one item so that every item has probability exactly 1/n of being returned, even though n was unknown until the end.
The difficulty is that the correct probability for each item depends on n, and you learn n only after the last item has gone by. A fixed rule such as "keep each item with probability p" cannot work. The rule has to adapt to how many items have been seen so far.
The Idea: Make the Answer Correct at Every Prefix
Don't aim only for a correct answer at the end. Aim for a correct answer after every item. Suppose that after reading i − 1 items, your held item is a uniform choice from those i − 1 items, so each has probability 1/(i − 1). Item i arrives. In a uniform choice from i items, the new item should win with probability 1/i. So:
- With probability 1/i, replace the held item with item i.
- Otherwise, keep the held item.
That is the whole algorithm. The first item is always taken (probability 1/1), the second replaces it half the time, the third replaces the current choice one time in three, and so on.
The Implementation
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 chosenThe details that matter:
enumerate(..., start=1)makesithe count of items seen including the current one. The replacement probability is 1/i with this 1-based count. With a 0-based index you would need1/(i+1), and mixing the two conventions is the most common bug in this algorithm.rng.randrange(i)returns an integer in0..i-1, each with probability exactly 1/i. Testing== 0therefore succeeds with probability exactly 1/i. Fori == 1it always succeeds, so the first item is always taken.- The function uses O(1) memory: one held item and one counter. It works on any iterable, including generators that cannot be rewound.
- The
rngparameter lets you pass a seededrandom.Randominstance for reproducible runs.
Why Every Item Ends Up with Probability 1/n
Fix an item xᵢ. For it to be returned, two things must happen:
- It is selected when it arrives, with probability 1/i.
- No later item j (for j = i + 1, …, n) replaces it. Item j fails to replace it with probability (j − 1)/j.
The random draws are independent, so we multiply:
P(xᵢ returned) = (1/i) · (i/(i+1)) · ((i+1)/(i+2)) · … · ((n−1)/n)
Each numerator cancels the previous denominator. Everything cancels except the 1 at the start and the n at the end:
P(xᵢ returned) = 1/n
This holds for every i, including i = 1 (selected with probability 1) and i = n (selected with probability 1/n, nothing after it).
Here is the product written out for a stream of four items:
| Item | Picked on arrival | Survives item 2 | Survives item 3 | Survives item 4 | Total |
|---|---|---|---|---|---|
| x₁ | 1 | 1/2 | 2/3 | 3/4 | 1/4 |
| x₂ | 1/2 | — | 2/3 | 3/4 | 1/4 |
| x₃ | 1/3 | — | — | 3/4 | 1/4 |
| x₄ | 1/4 | — | — | — | 1/4 |
Early items are easy to pick and must survive many challenges. Late items are hard to pick and face few challenges. The two effects balance exactly.
The Anytime Property
The invariant holds after every prefix, so the algorithm never depends on knowing n. You can stop the stream at any point, such as when a socket closes, a file ends, or a time budget runs out, and the held item is a uniform sample of everything seen so far. This matters in practice. A monitoring process can report "a random request from the last hour" on demand without pausing the stream.
A Quick Sanity Check
A seeded simulation shows the counts are roughly equal. A later chapter covers proper statistical testing. This check only catches gross mistakes.
import random
from collections import Counter
def sample_one(stream, rng=random):
chosen = None
for i, item in enumerate(stream, start=1):
if rng.randrange(i) == 0:
chosen = item
return chosen
rng = random.Random(12345)
trials = 200_000
counts = Counter(sample_one(range(5), rng) for _ in range(trials))
for x in range(5):
print(x, round(counts[x] / trials, 4)) # each should be close to 0.2Each frequency should land within about ±0.003 of 0.2. If item 0 or item 4 is far off, check the replacement probability first.
Cost
| Resource | Cost | Notes |
|---|---|---|
| Time | O(n) | One constant-time step per item |
| Memory | O(1) | One item plus one integer counter |
| Random numbers | n | One draw per item, including the first |
| Expected replacements | Hₙ ≈ ln n + 0.577 | Sum of 1/i for i = 1..n |
The last row follows from linearity of expectation. Item i causes a replacement with probability 1/i, so the expected number of replacements is 1 + 1/2 + … + 1/n, the n-th harmonic number. For a billion items that is only about 21 replacements. The algorithm still spends a random draw on every item, even though almost all draws say "keep." Algorithm L, covered later, removes that waste by computing how many items to skip.
Edge Cases
Empty stream
sample_one([]) returns None. If None can also be a real item in your stream, the caller cannot tell "empty stream" apart from "picked a None." Use a sentinel or raise an error:
import random
_EMPTY = object()
def sample_one_strict(stream, rng=random):
chosen = _EMPTY
for i, item in enumerate(stream, start=1):
if rng.randrange(i) == 0:
chosen = item
if chosen is _EMPTY:
raise ValueError("cannot sample from an empty stream")
return chosen
print(sample_one_strict([None, None, 7], random.Random(1)))Float comparisons instead of integer draws
A tempting variant is if rng.random() < 1 / i:. It is close, but not exact. random() returns one of 2⁵³ evenly spaced doubles, and 1/i is rounded to the nearest double, so the acceptance probability differs from 1/i by roughly 2⁻⁵³. That bias is negligible for most uses. randrange(i) == 0 is exact and no slower, so it is the better default. Never use rng.getrandbits(32) % i == 0 or similar modulo tricks. Unless i is a power of two, they favor small remainders.
Holding references
The algorithm holds one item, but in Python it holds a reference. If the stream reuses a mutable buffer, for example a reader that yields the same bytearray object refilled each time, the "chosen" item will silently change as later data arrives. Copy the item when you select it if the producer reuses objects.
Reproducibility
Passing rng=random uses the global generator, which any other code may also be consuming. For reproducible experiments and tests, pass a dedicated random.Random(seed). Seed it once outside the loop, never per item.
From One Item to k
The structure carries over directly. Instead of "replace the single held item with probability 1/i," Algorithm R keeps k slots and lets item i enter with probability k/i, evicting a uniformly chosen slot. The telescoping argument changes only slightly, and the anytime property and O(n) time stay the same. The next chapter builds that version.
Exercise
A stream has 10 items. What is the probability that the first item is the one returned by sample_one? Compute it from the product of survival probabilities rather than by quoting the result.
Show answer
The first item is picked with probability 1, then must survive items 2 through 10: (1/2)(2/3)(3/4)...(9/10). The product telescopes to 1/10.
Exercise
A colleague "simplifies" the algorithm to replace the held item with probability 1/2 at every step. For a stream of n items, what is the probability that the last item is returned, and what is the probability that the first item is returned?
Show answer
The last item is returned with probability 1/2, because it is picked with probability 1/2 and nothing follows it. The first item is picked with certainty, then must survive n − 1 coin flips, so it is returned with probability (1/2)^(n−1). The rule heavily favors recent items, which makes it an exponentially decaying sample, not a uniform one.
Exercise
About how many times does the held item change when sample_one runs over a stream of 1,000 items? What does this suggest about the cost of drawing one random number per item?
Show answer
The expected number of changes is H_1000 = 1 + 1/2 + ... + 1/1000 ≈ ln(1000) + 0.577 ≈ 7.49. Roughly 992 of the 1,000 random draws only confirm "keep," so a method that jumps directly to the next replacement, as Algorithm L does, can avoid most of the random-number calls.
Exercise
Rewrite the replacement test for a loop that uses 0-based indices (for i, item in enumerate(stream)) so that the algorithm stays correct.
Show answer
Use if rng.randrange(i + 1) == 0: chosen = item. With 0-based i, the number of items seen so far is i + 1, so the replacement probability must be 1/(i + 1). Writing rng.randrange(i) would raise an error at i = 0 and give later items the wrong probability.