Skip to content

Instantly share code, notes, and snippets.

@whiler
Created January 5, 2017 09:28
Show Gist options
  • Save whiler/a06b630800b5a3534b74d33b43ff4a7c to your computer and use it in GitHub Desktop.
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
# 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