imashutosh51

reservoir sampling

Apr 16th, 2026
38
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.87 KB | None | 0 0
  1. '''
  2. Problem: You will get a stream of numbers and your job is to pick an element randomly from 1 to i where i is the current elment.
  3.  
  4. so at the ith timestamp, you have to choose a number from 1 to i given probability of getting choosen of all numbers should be same.
  5. so if you put the random number in [1,i], the probability of getting i to be chosen is same as other numbers ie. 1/i so for every i, get a random number out of [1,i] and if number=i else let the result be previous number.
  6. '''
  7. import random
  8.  
  9. def reservoir_sampling(stream):
  10.     result = None
  11.     i = 0
  12.  
  13.     for val in stream:
  14.         i += 1
  15.        
  16.         # pick current element with probability 1/i
  17.         if random.randint(1, i) == i:
  18.             result = val
  19.         # else: keep previous result
  20.  
  21.     return result
  22.  
  23. for i in range(100):
  24.     print(reservoir_sampling([i for i in range(100)]),end=' ')
Advertisement
Add Comment
Please, Sign In to add comment