Last active
April 20, 2020 13:42
-
-
Save imakecodes/897d5ef06c194633549b21991a686d7e 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 bisect import bisect | |
from random import random | |
def weighted_choice(choices): | |
if not choices: | |
return None | |
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] | |
choices = [(1, 2), (2, 6), (3, 2)] | |
v1 = 0 | |
v2 = 0 | |
v3 = 0 | |
for i in range(100000): | |
v = weighted_choice(choices) | |
if v == 1: | |
v1 += 1 | |
if v == 2: | |
v2 += 1 | |
if v == 3: | |
v3 += 1 | |
print(v1, v2, v3) # (19906, 60172, 19922) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment