带概率的抽奖系统
- 为每个奖品设置不同的中奖概率,按照概率来抽取奖品。import random
prizes = {'iphone15': 0.01, 'airpods': 0.05, 'mechanicalkeyboard': 0.1, 'gamingmouse': 0.2, 'cup': 0.64}
def lucky_draw():r = random.random() # 生成0到1之间的随机数cur = 0for prize, prob in prizes.items():cur += probif r <= cur:return prize
模拟100个人抽奖
draw_results = {}for _ in range(100):result = lucky_draw()if result in draw_results:draw_results[result] += 1else:draw_results[result] = 1
for prize, count in draw_results.items():print(f'{prize}被抽中{count}次')