Weighted Reservoir Sampling

medium
Unit 15 · Sampling & Regression0/2 to milestone

Sample k items without replacement from a stream where each item has a weight, in one pass (the A-Res algorithm of Efraimidis & Spirakis):

for each item with weight ww, draw u∼U(0,1)u \sim U(0, 1) and give it the key u1/wu^{1/w}; keep the k items with the largest keys.

Implement weighted_sample(stream, k, seed=0) where stream yields (item, weight) pairs with positive weights. Draw one rng.random() per item, in order, from np.random.default_rng(seed), and return the kept items sorted by key, largest first. Use a min-heap of size k.

#sampling#streaming#algorithms2 visible + 1 hidden tests
solution.py · Python 3.13
Loading editor…
Run your code to see results. ⌘↵ to run · ⌘⇧↵ to submit
Weighted Reservoir Sampling · TechGradify