Created
March 6, 2014 02:44
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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