Skip to content

Instantly share code, notes, and snippets.

@etng
Created March 6, 2014 02:44
Show Gist options
  • Save etng/9381254 to your computer and use it in GitHub Desktop.
Save etng/9381254 to your computer and use it in GitHub Desktop.
use bisect to random get items with weighted probability, the weight field can be specified
import random
import collections
import bisect
def weighted_random_choice(candidates, field='weight'):
'''
use bisect to random get items with weighted probability, the weight field can be specified
'''
prepared_candidates = {}
total_weight = 0
for candidate in candidates:
total_weight+= candidate[field]
prepared_candidates[total_weight]=candidate
od = collections.OrderedDict(sorted(prepared_candidates.items(), key=lambda t: t[0]))
idx = bisect.bisect(od.keys(), random.randint(0, total_weight-1))
print idx
return od.values()[idx]
if __name__=='__main__':
weighted_things = [
{'weight':18, 'name': 'A', 'event':'Meet a Bomb',},
{'weight':16, 'name': 'B', 'event':'Meet a beast',},
{'weight':14, 'name': 'C', 'event':'Meet a love',},
{'weight':30, 'name': 'D', 'event':'Meet a hate',},
]
for i in range(1, 100):
print weighted_random_choice(weighted_things)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment