功能描述
抽奖系统包含如下特点:
1、可给不同抽奖者设置不同的权重
2、先从价值高的奖品开始抽
3、已经中奖的人,不再参与后续的抽奖
代码
第一个数字表示某一个用户的中奖编号,第二个数字表示该用户的中奖权重。
名单.txt
内容为:
1:20
2:10
3:8
4:6
5:6
6:3
7:2
8:1
main.py
内容为:
# 抽奖工具
# -*- coding:utf-8 -*-
from random import choice
def read_name_list(txt_name):
with open(txt_name, 'r', encoding='utf-8') as f:
txt_list = f.readlines()
for i in range(len(txt_list)):
txt_list[i] = txt_list[i].rstrip('\n')
return txt_list
def lottery_draw(name_list, prize_box):
full_number = []
for name in name_list:
number, weight = name.split(':')
full_number += [number] * int(weight)
for prize in prize_box:
luck_number = choice(full_number)
print('【{}】的中奖用户编号为:{}'.format(prize, luck_number))
full_number = [i for i in full_number if i != luck_number]
if __name__ == '__main__':
# 导入名单
name_list = read_name_list('名单.txt')
# 设置奖项
prize_box = ['汽车', '电脑', '杯子', '香蕉', '5毛红包']
# 抽奖
lottery_draw(name_list, prize_box)
运行结果如下:
【汽车】的中奖用户编号为:5
【电脑】的中奖用户编号为:1
【杯子】的中奖用户编号为:3
【香蕉】的中奖用户编号为:2
【5毛红包】的中奖用户编号为:6
验证
加一个统计函数statistics
、修改下lottery_draw
的输入输出,然后抽奖1000000次,看看结果是否和我们设想的一样不同用户中奖权重不同。
main.py
完整代码如下:
# 抽奖工具
# -*- coding:utf-8 -*-
from random import choice
from collections import Counter
def read_name_list(txt_name):
with open(txt_name, 'r'