加权随机算法和洗牌算法

加权随机算法和洗牌算法

加权随机算法

# @Time : 2019/6/20 14:43 
# @Author : panky_pan
# @File : draw_manager.py 
# @Software: PyCharm
"""
算法阐明:
加权随机算法,将一个数域(例如0-1000)进行分域,对每块区域进行编号,将区域编号与事件object进行一一映射
每块区域占数域的比值代表这个区域的权重,即该区域所代表的object在某种情况下事件发生的概率。
利用Python的random.randint(),在该数域内随机产生一个数字,判断该数字属于
哪个区域,获得区域编号,即可获得区域代表的object
"""
import random


TEAM_DESC = {0: "OTHERS", 1: "PHX", 2: "NYK", 3: "BKN", 4: "CLE", 5: "LAL", 6: "NOP"}  # 数字编号代表的队伍


class DrawManager(object):

    def __init__(self):
        self.team_draw_probabilities = [100, 250, 200, 150, 100, 100, 100]  # 每支队伍被抽中的权重

    def weight_choice(self, weight):
        """根据权重比随机产生一个队伍代号"""
        t = random.randint(0, int(sum(weight))-1)
        for index, val in enumerate(weight):
            t -= val
            if t < 0:
                return index

    def get_random_team(self):
        """
        :return:
        """
        random_team_number = self.weight_choice(self.team_draw_probabilities)
        random_team = TEAM_DESC.get(random_team_number, None)
        return random_team_number, random_team


if __name__ == "__main__":
    draw = DrawManager()
    count_list = []
    for i in range(0, 1000):  # 抽取1000次
        team_number, team = draw.get_random_team()
        count_list.append(team_number)

    # 每支队伍被抽中的次数
    print("PHX: %s" % count_list.count(1))
    print("NYK: %s" % count_list.count(2))
    print("BKN: %s" % count_list.count(3))
    print("CLE: %s" % count_list.count(4))
    print("LAL: %s" % count_list.count(5))
    print("NOP: %s" % count_list.count(6))
    print("OTHERS: %s" % count_list.count(0))

上一篇:URAL 1182. Team Them Up!


下一篇:解读vue-element-admin登录逻辑permission.js