Skip to content

Instantly share code, notes, and snippets.

@ayuLiao
Last active November 28, 2024 06:58
Show Gist options
  • Save ayuLiao/c88718cb37139468b18b37f9f9a0888e to your computer and use it in GitHub Desktop.
Save ayuLiao/c88718cb37139468b18b37f9f9a0888e to your computer and use it in GitHub Desktop.
python抽奖代码
# turntable.py 幸运转盘抽奖
import random
import bisect
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))]
# 返回list中tuple的索引为0的元素,这里就是iphone、ipad、mac
prizename = WeightRandom([('iphone',20),('ipad',30),('mac',50)])
print(prizename)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment