imashutosh51

reservoir sampling of k items

Apr 16th, 2026 (edited)
39
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.80 KB | None | 0 0
  1. Given a stream of n elements where n may be very large or unknown, randomly select exactly k elements such that every element has equal probability of being chosen.
  2.  
  3. The solution must process the stream in a single pass using only O(k) extra space.
  4.  
  5. import random
  6. def reservoir_sampling_k(stream, k):
  7.     reservoir = []
  8.     i = 0
  9.  
  10.     for val in stream:
  11.         i += 1
  12.  
  13.         if i <= k: #first K numbers should get the chance to be chosen first
  14.             reservoir.append(val)
  15.         else: #now if current index is more than k then take a random guess from 1 to i, if the random guess is less than equal to k then push the current element in that index
  16.             j = random.randint(1, i)
  17.            
  18.             if j <= k:
  19.                 reservoir[j - 1] = val  # replace
  20.  
  21.     return reservoir
Advertisement
Add Comment
Please, Sign In to add comment