The problem
Choose k items fairly from stream, which can be read only once, item by item, and whose length is not known in advance. Use reservoir sampling exactly as lesson 7 describes, with the random function you are given:
- keep the first
kitems, in slots 0 to k − 1, in order; - for each later item, the one at position
i(counting from 0), callrand(i + 1)once to getjfrom 0 to i; ifj < k, put the item in slotj.
Return the list of slots. If the stream has fewer than k items, return all of them. Do not call rand for the first k items.
# rand returns 1, 0, 3, 2 in turn
sample(iter("abcdef"), 2, rand) # ['d', 'c']
sample(iter([7, 8]), 5, rand) # [7, 8]
Limits
- The stream may be a generator: it has no
len(), and it can be looped over only once. It has up to 300,000 items. - The tests pass fixed “random” answers, so the right sample is known exactly. Two tests try every possible run of answers and check that every set of items is chosen equally often.
Builds on MATH-7 Probability for algorithms.
Continue on a laptop
Practice runs Python in the browser and needs a keyboard and a wider screen. Read the problem and open hints here, then write your solution on a laptop. Progress is saved per browser for now, so hints opened here stay on this device.
Need a hint?0 of 3 opened
- Hint 1Nudge
- Hint 2Approach Open hint 1 first
- Hint 3Pseudocode Open hint 2 first
- Worked solutionlast resort Opens after all 3 hints
Ctrl + Enter runs the tests. Tab indents; press Esc, then Tab, to leave the editor.
| # | Test | Result | Reads · time |
|---|---|---|---|
| 1 | The example | Not run | |
| 2 | Fewer items than k | Not run | |
| 3 | k is 0 | Not run | |
| 4 | Which calls to rand | Not run | |
| 5 | Every outcome, 5 items | Not run | |
| 6 | Every outcome, 6 items | Not run | |
| 7 | A hundred items | Not run | |
| 8 | A generator | Not run | |
| 9 | 300,000 items | Not run |