Skip to content

Instantly share code, notes, and snippets.

@vicapow
Last active December 20, 2015 11:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vicapow/6124529 to your computer and use it in GitHub Desktop.
Save vicapow/6124529 to your computer and use it in GitHub Desktop.
randomly pull items out of a list using weights for each item (with replacement)
from math import *
import random
w = [0.9,0.1] #faster if the weighted list is pre-sorted, descending
p = ['victor', 'powell']
N = len(w)
p2 = []
for i in range(N):
stop = 0
n = random.random()
for j in range(N):
stop += w[j]
if n < stop:
p2.append(p[j])
break
print p2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment