写一个摇号程序,输入是 users 和 quota:

xxxxxxxxxx# coding: utf8import randomclass Node(object): def __init__(self, start_index, end_index, name): self.start_index = start_index self.end_index = end_index self.name = name self.chance = end_index - start_index + 1 def __str__(self): return "Node{name=%s, start_index=%d, end_index=%d, chance=%d}" % ( self.name, self.start_index, self.end_index, self.chance) __repr__ = __str__def lot(users, quota): if len(users) <= quota: return users.keys() total_length = 0 start_index = 0 user_list = [] for name, chance in users.iteritems(): total_length = total_length + chance end_index = start_index + chance - 1 user_list.append(Node(start_index, end_index, name)) start_index = end_index + 1 chosen = [] while len(chosen) < quota: # 生成一个 [0, total_length-1] 之间的随机数 n = random.randint(0, total_length - 1) # 判断谁中奖了 ind = None for ind, node in enumerate(user_list): if node.start_index <= n <= node.end_index: break node = user_list[ind] chosen.append(node.name) # 修改 total_length total_length = total_length - node.chance # 修改 user_list user_list.pop(ind) for i in range(ind, len(user_list)): user_list[i].start_index -= node.chance user_list[i].end_index -= node.chance return chosendef test(): # map `name` to `chance` users = {"Tim": 2, "Lorriane": 2, "YuNai": 10} print(lot(users, 2))if __name__ == "__main__": test()