Skip to content

Instantly share code, notes, and snippets.

@lykkin
Last active August 29, 2015 14:21
Show Gist options
  • Save lykkin/b4d0c5610e664485dad4 to your computer and use it in GitHub Desktop.
Save lykkin/b4d0c5610e664485dad4 to your computer and use it in GitHub Desktop.
weighted choice
from random import random
class thing:
def __init__(self, value, weight=1):
self.value = value
self.weight = weight
def __str__(self):
return str(self.value) + ' ' + str(self.weight)
things = [thing(x) for x in range(10)]
def pick():
total_weight = sum(map(lambda thing: thing.weight, things))
choice_weight = total_weight*random()
chosen = None
i = 0
while choice_weight > 0:
chosen = things[i]
choice_weight -= chosen.weight
i += 1
chosen_weight[chosen.weight] += 1
chosen.weight /= 10
for th in things:
th.weight += 1
return chosen
chosen = [0]*10
chosen_weight = [0]*100
for _ in range(1000000):
ch = pick()
chosen[ch.value] += 1
diff = max(chosen) - min(chosen)
print diff
for c in range(100):
print c, chosen_weight[c]
print chosen
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment