BLOGLLM Logo
Go Pro
Guest
Not signed in
All BlogsCoursesPracticeInterview prepSeriesTagsBookmarksPricing
Log in
All BlogsCoursesPracticeTagsBookmarksPricing
My PrepProblemsStudy PlansResearch PapersRoadmapInterviewContestsLeaderboardGames
Articles
Practice / Data processing and features44 of 54 in topic

806. Sample k items from a stream with reservoir sampling

MediumData processing and features

Why it matters Sampling production prompts for evaluation and logging pipelines both need fixed-size uniform samples of unbounded streams.

You want a uniform random sample of k log lines or prompts from a stream too big to store. Reservoir sampling keeps exactly k items and gives every item the same chance k / n of ending up in the sample.

Write reservoir(stream, k, seed). Use rng = random.Random(seed). Keep the first k items. For the item at 0-based index i >= k, draw j = rng.randint(0, i) (inclusive) and if j < k replace slot j with it. Return the reservoir list. If the stream has fewer than k items, return them all.

Functiondef reservoir(stream, k, seed)

Example 1

Input: reservoir(['a', 'b'], 5, 0)

Output: ['a', 'b']

Example 2

Input: stream = range(100), k = 5, seed = 42

Output: [35, 17, 52, 10, 99]

Example 3

Input: stream = iter(range(1000)), k = 3, seed = 7

Output: [929, 989, 360]

Constraints

  • Python 3 standard library. Code runs in your browser.
  • Your code must pass all 5 tests to be accepted.
Hint 1

Fill the reservoir with the first k items.

Hint 2

For later items draw j from 0 to i inclusive; replace slot j only when j < k.

Common mistakes
  • Drawing from 0 to i - 1 or 0 to n, which biases toward early or late items.
  • Calling len(stream), which fails on a real iterator.
Understand the idea

When item i arrives (0-based), it should be in the sample with probability k / (i + 1). Drawing j uniformly from 0..i and keeping the item when j < k does exactly that, and the slot it replaces is random. By induction every item seen so far stays in with probability k / (i + 1).

Worked example

a stream shorter than k is returned whole.

j = randint(0, i); if j < k: res[j] = item
Topics
Data processing and features
Similar questions
  • Split a dataset so every class keeps its shareMedium
  • Bin a feature into quantile buckets learned from training dataMedium
  • Frequency-encode a category with a shared bucket for rare and unseen valuesMedium
  • Generate K-fold train and validation index splitsMedium
All Data processing and features problems
Report
806 / 903
Python 3solution.pyPython idle
1
2
3
4
5
import random
def reservoir(stream, k, seed):
# your code here
pass
​

Run checks these cases in your browser, no sign-in needed. Submit checks all 5 tests.

Ctrl/Cmd + Enter to run
© BlogLLM, Bengaluru, IndiaAboutTermsPrivacyRefundsDMCAContactRSS