Skip to content

Instantly share code, notes, and snippets.

@imakecodes
Last active April 20, 2020 13:42
Show Gist options
  • Save imakecodes/897d5ef06c194633549b21991a686d7e to your computer and use it in GitHub Desktop.
Save imakecodes/897d5ef06c194633549b21991a686d7e to your computer and use it in GitHub Desktop.
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