Skip to content

Instantly share code, notes, and snippets.

@c1ay
Last active May 25, 2017 03:11
Show Gist options
  • Save c1ay/8a89ebc4b6655f668d2390ef0779ee50 to your computer and use it in GitHub Desktop.
Save c1ay/8a89ebc4b6655f668d2390ef0779ee50 to your computer and use it in GitHub Desktop.
python 权重随机
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