Skip to contentKEEP THE CRAFTTHE SANCTUARY

Simulate Reservoir Sampling

Keep a uniform sample of k items from a stream with Algorithm R, using given random numbers so the result can be checked.

The problem

Reservoir sampling keeps a uniform random sample of k items from a stream whose length you do not know in advance. To make the result checkable, the random numbers are given to you. Implement reservoir_sample(values, k, draws): - Put the first k values into the reservoir. - For each later index i (from k to len(values) - 1), the random number j = draws[i - k] is between 0 and i, as if it came from random.randint(0, i). If j < k, values[i] replaces reservoir[j]; otherwise values[i] is skipped. - Return the final reservoir, which always holds k items. You can assume 1 <= k <= len(values) and len(draws) == len(values) - k. Example: values = [10, 20, 30, 40, 50], k = 2, draws = [1, 3, 0]. Start with [10, 20]; 30 replaces slot 1, giving [10, 30]; 40 is skipped because 3 >= 2; 50 replaces slot 0. The answer is [50, 30].

Starter code

def reservoir_sample(values, k, draws):
    pass

Public examples

  1. values = [10, 20, 30, 40, 50], k = 2, draws = [1, 3, 0]gives[50, 30]
  2. values = [1, 2, 3, 4], k = 2, draws = [2, 3]gives[1, 2]

Solving it in the practice book needs an active paid plan.

Open it in the practice book
One thought at a time.