# -*- coding:utf-8 -*- # __author__ = 'yuzhongfu' # __mktime__ = '15/10/20' import time import random def start(dict_info): """""" dict_computer = {} # 获得中奖几率总和 rate_count = sum(dict_info.values()) rate_station = 0 # 根据中奖几率把各个奖项放入中奖的区域 for id,rate in dict_info.items(): # 此奖项ID的中奖值的范围是rate_station =< 奖值 <= rate_station+rate dict_computer[id] = [rate_station,rate_station+rate] rate_station = rate_station+rate # 随机抽中一个中奖的值 selected_rate = random.random()*rate_count # 根据中奖的值选出中奖的ID号 selected_id = None for id,[min_rate,max_rate] in dict_computer.items(): if selected_rate >= min_rate and selected_rate <= max_rate: selected_id = id break return selected_id if __name__ == "__main__": dict_info = {"1":0.1,"2":0.1,"3":0.1,"4":0.1,"5":0.1,"6":0.1,"7":0.4} # 奖项和对应的中奖几率 dict_info = {"1":30.1,"2":20.2,"3":10.3,"4":20.4} dict_selected = {} # 测试中奖算法的正确性 for item in range(1000200): id = start(dict_info) dict_selected[id] = dict_selected.get(id,0) + 1 # 打印出中奖项以及对应的次数 for item in dict_selected.items(): print item
python -- 抽奖
最新推荐文章于 2024-04-13 00:11:06 发布