Created
January 5, 2017 09:28
-
-
Save whiler/a06b630800b5a3534b74d33b43ff4a7c to your computer and use it in GitHub Desktop.
Chooses k unique random elements from a population sequence with odds like random.sample
This file contains 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
# coding=utf-8 | |
import random | |
__author__ = "[email protected]" | |
def sample(population, k, odds=lambda item: 1.0): | |
""" | |
Chooses k unique random elements from a population sequence with odds. | |
like random.sample | |
""" | |
result = [None] * k | |
selected = set() | |
size = len(population) | |
for i in range(k): | |
while True: | |
pos = int(size * random.random()) | |
if pos in selected: | |
continue | |
target = population[pos] | |
if odds(target) >= random.random(): | |
selected.add(pos) | |
result[i] = target | |
break | |
return result |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment