Created
September 9, 2020 19:16
-
-
Save ahmed4end/d62b889fab49fda6a0bf0f0802fb6872 to your computer and use it in GitHub Desktop.
weighted choices
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] | |
a = [weighted_choice([(2,10), (1,10), (-1,1)]) for i in range(100)] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment