Sub topic 1
Streams: One Pass, Unknown Length, Limited Memory
Prerequisites
This chapter assumes you can read Python loops and iterators, know what a uniform distribution and independent events are, and can follow Big-O notation. Later chapters use proof by induction.
The Streaming Model
A stream is a sequence of items that you read one at a time, in order. Log lines, network packets, and rows from a huge file all arrive this way. The streaming model puts three limits on what you can do:
- One pass. You see each item once. You cannot go back to an earlier item.
- Unknown length. You don't know the total count
nuntil the stream ends, and some streams never end. - Bounded memory. You can store only a small, fixed amount, usually
O(k)for a sample of sizek, no matter how largengets.
What a Uniform Sample Without Replacement Means
A uniform sample of k items without replacement is a set of k distinct positions from the stream. Every possible set of k positions must be equally likely, which means each item ends up in the sample with probability k/n. "Without replacement" means no position can be picked twice.
Why the Naive Approaches Fail
| Approach | Problem |
|---|---|
| Store everything, then call `random.sample` | Memory grows as `O(n)`, and you never get an answer from a stream that doesn't end |
| Keep each item with a fixed probability `p` | You need `p = k/n`, but `n` is unknown. The sample size also varies at random instead of being exactly `k` |
Warm-Up: Keeping One Random Item
Start with k = 1. Keep one candidate. When item i arrives (counting from 1), replace the candidate with item i with probability 1/i.
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
print(sample_one(range(100)))Here is why this works. Item i is chosen at step i with probability 1/i. It survives step j > i with probability (j−1)/j. The product of these factors telescopes:
(1/i) · (i/(i+1)) · ((i+1)/(i+2)) · … · ((n−1)/n) = 1/n
So every item ends up chosen with probability 1/n. The algorithm uses O(1) memory and never needs to know n.
Exercise
With a stream of 4 items, what is the probability that item 2 is the final choice? Show the factors.
Show answer
Item 2 is chosen at step 2 with probability 1/2. It survives step 3 with probability 2/3 and step 4 with probability 3/4. The product is (1/2)(2/3)(3/4) = 1/4 = 1/n.
Exercise
A common bug writes rng.randrange(i + 1) == 0 with enumerate(stream, start=1). What goes wrong?
Show answer
The first item is kept with probability 1/2 instead of 1. If the stream has one item, the function can return None, and every later item is kept with probability 1/(i+1), so the result is no longer uniform.