Skip to content

Instantly share code, notes, and snippets.

@ahmed4end
Created September 9, 2020 19:16
Show Gist options
  • Save ahmed4end/d62b889fab49fda6a0bf0f0802fb6872 to your computer and use it in GitHub Desktop.
Save ahmed4end/d62b889fab49fda6a0bf0f0802fb6872 to your computer and use it in GitHub Desktop.
weighted choices
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