http://eli.thegreenplace.net/2010/01/22/weighted-random-generation-in-python/
Love this fast and elegant one.
class WeightedRandomGenerator(object):
def __init__(self, weights):
self.totals = []
running_total = 0
for w in weights:
running_total += w
self.totals.append(running_total)
def next(self):
rnd = random.random() * self.totals[-1]
return bisect.bisect_right(self.totals, rnd)
def __call__(self):
return self.next()
1
mengzhuo 2014-12-08 19:24:47 +08:00
前段时间考察过这个算法,在总量小的情况下(<1000)
用Python自带的for 循环比 bisect效率高 |
2
koykoi 2014-12-08 19:42:40 +08:00
Roulette Wheel
|
4
efi 2014-12-09 01:11:16 +08:00 1
numpy.random.choice(1, p=weights)
|