Skip to content

Instantly share code, notes, and snippets.

@Flushot
Created March 3, 2015 04:03
Show Gist options
  • Select an option

  • Save Flushot/f96dc9d184ec001db084 to your computer and use it in GitHub Desktop.

Select an option

Save Flushot/f96dc9d184ec001db084 to your computer and use it in GitHub Desktop.
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