Skip to content

Instantly share code, notes, and snippets.

@ilius
Created January 30, 2016 13:02
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 ilius/7b69c0c56018a2b700f4 to your computer and use it in GitHub Desktop.
Save ilius/7b69c0c56018a2b700f4 to your computer and use it in GitHub Desktop.
import random
def weighted_choice(choices):
if isinstance(choices, dict):
choices = choices.items()
total = sum(w for c, w in choices)
r = random.uniform(0, total)
upto = 0
for c, w in choices:
if upto + w >= r:
return c
upto += w
assert False, "Shouldn't get here"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment