Created
March 3, 2015 04:03
-
-
Save Flushot/f96dc9d184ec001db084 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| from random import random | |
| from bisect import bisect | |
| def weighted_choice(choices): | |
| values, weights = zip(*choices) | |
| total = 0 | |
| cum_weights = [] | |
| for w in weights: | |
| total += w | |
| cum_weights.append(total) | |
| x = random() * total | |
| i = bisect(cum_weights, x) | |
| return values[i] | |
| for i in range(100): | |
| print weighted_choice([ | |
| ('a', 0.1), | |
| ('b', 0.5), | |
| ('c', 0.9) | |
| ]), |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment