Skip to content

Instantly share code, notes, and snippets.

@ColtonPhillips
Created March 10, 2014 02:24
Show Gist options
  • Save ColtonPhillips/9458478 to your computer and use it in GitHub Desktop.
Save ColtonPhillips/9458478 to your computer and use it in GitHub Desktop.
Given an array of elements which are composed of a tuple of a string label and integer weight, chooses one randomly while factoring in the relative weightings, and returns the label.
from bisect import bisect
from random import random
def weighted_choice(choices):
values, weights = zip(*choices)
total = 0
cum_weights = []
for w in weights:
total += w
cum_weights.append(total)
guess = random () * total
index = bisect(cum_weights, guess)
return values[index]
def main():
my_choices = [('a',1),('b',0),('c',2),('d',3),('e',0)]
my_results = []
for i in range (6000):
answer = weighted_choice(my_choices)
my_results.append(answer)
print("A:{}\nB:{}\nC:{}\nD:{}\nE:{}\n".format(
my_results.count('a'),
my_results.count('b'),
my_results.count('c'),
my_results.count('d'),
my_results.count('e')))
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment