Python利用带权重随机数解决抽奖和游戏爆装备问题
关于带权随机数 在抽奖和游戏爆装备中的运用 #coding=utf-8 import random def weighted_random(items): total = sum(w for _,w in items) n = random.uniform(0,total)#在饼图扔骰子 for x,w in items:#遍历找出骰子所在的区间 if n<w: break n -= w return x print weighted_random([('iphone',50)]) 上面的代码够直观,不过细心的会发现,每次都会计算total,每次都会线性遍历区间进行减操作.其实我们可以先存起来,查表就行了.利用accumulate+bisect二分查找. #coding=utf-8 class WeightRandom: def __init__(self,items): weights = [w for _,w in items] self.goods = [x for x,_ in items] self.total = sum(weights) self.acc = list(self.accumulate(weights)) def accumulate(self,weights):#累和.如accumulate([10,40,50])->[10,50,100] cur = 0 for w in weights: cur = cur+w yield cur def __call__(self): return self.goods[bisect.bisect_right(self.acc,random.uniform(0,self.total))] wr = WeightRandom([('iphone',50)]) print wr() (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |