Sub topic 5
Algorithm R: A Reservoir of k Items
This chapter assumes you know basic Python iterators, elementary probability, and the single-item reservoir from the previous chapter. That chapter replaced the kept item with the i-th item with probability 1/i. Algorithm R extends the same idea to a reservoir of k slots.
The working model
A reservoir is a fixed-size list that always holds a uniform sample of everything seen so far. Algorithm R maintains it in two phases:
- Fill phase. The first k items go straight into the reservoir. With only k items seen, keeping all of them is the only valid sample.
- Replacement phase. For each later item at 0-based index i (so it is the (i+1)-th item), draw a random integer j from 0 to i inclusive. If j < k, overwrite
reservoir[j]with the new item. Otherwise, discard it.
The test j < k succeeds with probability k/(i+1). That is the chance the new item would have of being in a uniform sample of size k drawn from the first i+1 items. When it does succeed, j is uniform over 0..k-1, so the evicted slot is chosen uniformly too. One random draw handles both decisions.
Implementation
import random
def reservoir_sample(stream, k, rng=random):
reservoir = []
for i, item in enumerate(stream):
if i < k:
reservoir.append(item)
else:
j = rng.randint(0, i) # inclusive: 0..i
if j < k:
reservoir[j] = item
return reservoir
if __name__ == "__main__":
rng = random.Random(42)
print(reservoir_sample(range(1_000_000), 5, rng))
print(reservoir_sample(iter("abc"), 5, rng)) # stream shorter than kSome details to note:
streamcan be any iterable, including a generator or a file object. The function reads each item once and never asks for the length.- If the stream has fewer than k items, you get all of them back. Callers should expect
len(result) <= k. - Passing an
rngobject makes runs reproducible, which you will need when testing.
A short trace
Take k = 2 and the stream A, B, C, D.
| Index i | Item | Draw j (range) | Action | Reservoir |
|---|---|---|---|---|
| 0 | A | none | fill | [A] |
| 1 | B | none | fill | [A, B] |
| 2 | C | 1 (0..2) | j < 2, replace slot 1 | [A, C] |
| 3 | D | 3 (0..3) | j ≥ 2, discard | [A, C] |
C was kept with probability 2/3 and D with probability 2/4. Both match k/(i+1).
Common errors
- Evicting with a second random draw. Code such as
if rng.random() < k/(i+1): reservoir[rng.randrange(k)] = itemis correct, but it spends two random numbers when one is enough. - Reordering expectations. The reservoir's order is not random. Early items tend to sit in their original slots. Shuffle the result if order matters downstream.
- Mixing up 0-based and 1-based indices. If you
enumerate(stream, start=1), the draw must becomerandint(1, i)with the testj <= k.
A later chapter proves that the final probability is k/n for every item, and another analyzes the cost.
Exercise
With k = 3, the item at 0-based index 9 arrives. What is the probability it enters the reservoir, and given that it enters, what is the probability it lands in slot 0?
Show answer
It enters with probability k/(i+1) = 3/10. Given that it enters, j is uniform over {0, 1, 2}, so it lands in slot 0 with probability 1/3.
Exercise
A colleague writes j = rng.randrange(i) with 0-based i. For i = k, what is the probability that the new item is kept, and what should it be?
Show answer
randrange(k) always returns a value below k, so the item is kept with probability 1. The correct probability is k/(k+1).