加权摇号(加权轮盘赌)算法

清华大佬耗费三个月吐血整理的几百G的资源,免费分享!....>>>

# coding: utf-8
import random
def chose(num_chose,weight,id): ## 输入摇号名额,参与摇号人员的ID和权重
    if len(weight) != len(id):
        return u"摇号人数与权重人数不等,请重新输入"
    else:
        num = len(id)
        l_weight = []
        for k in range(num):
            if k == 0:
                l_weight.append(weight[k])
            else:
                l_weight.append(l_weight[k-1]+weight[k]) ##计算累积权重
        luck_id = []      ##列表记录摇号结果
        for n in range(num_chose):
            luck_num = random.uniform(0,l_weight[num-1])  ##生成每次摇号的幸运值
            for m in range(num):
                if luck_num <= l_weight[m]:
                    luck_id.append(id[m])
                    break
        return luck_id


if __name__ == '__main__':
    num = 100 ##参与摇号的总人数
    weight = []
    for i in range(num):
        weight.append(random.uniform(0,1))  ## 生成随机权重,也可从屏幕或文件读取
    id = []
    for j in range(num):
        id.append(j+1)    ## 与权重对应的摇号人编码、姓名,实际可从文件或屏幕读取
    print u"摇号结果:",chose(3,weight,id) ## 试验设置名额为3