Last active
May 25, 2017 03:11
-
-
Save c1ay/8a89ebc4b6655f668d2390ef0779ee50 to your computer and use it in GitHub Desktop.
python 权重随机
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 bicsect | |
import itertools | |
class WeightedRandomGenerator(object): | |
def __init__(self, weights): | |
self.totals = [] | |
running_total = 0 | |
# py2 | |
for w in weights: | |
running_total += w | |
self.totals.append(running_total) | |
# py3 | |
self.totals = list(itertools.accumulate(weights)) | |
def random(self): | |
rnd = random.random() * self.totals[-1] | |
return bisect.bisect_right(self.totals, rnd) | |
def __call__(self): | |
return self.random() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment