Skip to content

Instantly share code, notes, and snippets.

@madisonmay
Created September 2, 2013 02:53
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 madisonmay/6408842 to your computer and use it in GitHub Desktop.
Save madisonmay/6408842 to your computer and use it in GitHub Desktop.
Random weighted choice generator function
import itertools, bisect
def weighted_choice(seq, weights):
cumulative_dist = itertools.accumulate(weights)
while True:
x = random.random() * cumdist[-1]
i = [bisect.bisect(cumulative_dist, x)]
yield seq[i]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment