Last active
February 4, 2020 21:02
-
-
Save pervognsen/e0896d13b8b8a52da36520b5faeb8302 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from random import * | |
# Classical reservoir sampling | |
def sample1(xs): | |
n = 0 | |
y = None | |
for x in xs: | |
n += 1 | |
if randrange(n) == 0: y = x | |
return y | |
# Reservoir sampling with bounded buffer | |
def sample2(xs, max_buf): | |
buf = [] | |
n = 0 | |
y = None | |
for x in xs: | |
buf.append(x) | |
n += 1 | |
if len(buf) == max_buf: | |
i = randrange(n) | |
if i < len(buf): y = buf[i] | |
buf.clear() | |
if buf: | |
i = randrange(n) | |
if i < len(buf): y = buf[i] | |
return y | |
print(sample2(range(10), 1)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment