Last active
June 23, 2016 07:15
-
-
Save narendranathjoshi/216ee6ddf38d0579ea58a7ab284136e5 to your computer and use it in GitHub Desktop.
Weighted Choice in Python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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