Skip to content

Instantly share code, notes, and snippets.

@narendranathjoshi
Last active June 23, 2016 07:15
Show Gist options
  • Save narendranathjoshi/216ee6ddf38d0579ea58a7ab284136e5 to your computer and use it in GitHub Desktop.
Save narendranathjoshi/216ee6ddf38d0579ea58a7ab284136e5 to your computer and use it in GitHub Desktop.
Weighted Choice in Python
def weighted_choice(choices):
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