python 19 lines · 5 steps

How reservoir sampling picks k items

Draw a uniform random sample of k items from a stream of unknown length in a single pass.

Explained by highlit
1import random
2from typing import Iterator, List
3 
4 
5def reservoir_sample(lines: Iterator[str], k: int) -> List[str]:
6 reservoir: List[str] = []
7 for i, line in enumerate(lines):
8 if i < k:
9 reservoir.append(line)
10 else:
11 j = random.randint(0, i)
12 if j < k:
13 reservoir[j] = line
14 return reservoir
15 
16 
17def sample_lines_from_file(path: str, k: int) -> List[str]:
18 with open(path, "r", encoding="utf-8") as fh:
19 return [line.rstrip("\n") for line in reservoir_sample(fh, k)]
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Reservoir sampling gives a uniform sample without knowing the total count up front.
  2. 2Replacing element j with probability k/(i+1) keeps every seen item equally likely.
  3. 3Streaming over an iterator lets you sample files larger than memory in one pass.

Related explainers

Share this explainer

Here's the card — post it anywhere.

How reservoir sampling picks k items — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code