我需要从加权集合中随机选取几个项目。重量较大的物品更容易被挑选。我决定在抽签后做这个模型。我觉得我的解决方案是很好的C++,但我认为它不适合做Python。在
Python是怎么做的?在def _lottery_winners_by_participants_and_ticket_counts(participants_and_ticket_counts, number_of_winners):
"""
Returns a list of winning participants in a lottery. In this lottery,
participant can have multiple tickets, and participants can only win
once.
participants_and_ticket_counts is a list of (participant, ticket_count)
number_of_winners is the maximum number of lottery winners
"""
if len(participants_and_ticket_counts) <= number_of_winners:
return [p for (p, _) in participants_and_ticket_counts]
winners = []
for _ in range(number_of_winners):
total_tickets = sum(tc for (_, tc) in participants_and_ticket_counts)
winner = random.randrange(0, total_tickets)
ticket_count_offset = 0
for participant_ticket_count in participants_and_ticket_counts:
(participant, ticket_count) = participant_ticket_count
if winner < ticket_count + ticket_count_offset:
winners.append(participant)
participants_and_ticket_counts.remove(participant_ticket_count)
break
ticket_count_offset += ticket_count
return winners
编辑:对不起,我刚才忘了这个,但是重量是一个整数,可以是几千。在
编辑:我想我的最终解决方案是基于@Flo的评论
注释我在Python2.7中工作,所以我创建了自己的accumulate()。它的工作方式与Python3中的accumulate()不同(我认为更好)。我的版本可以根据add函数从一个iterable元组中累积。
我还特别了解,participants_and_ticket_counts是一个可变的列表,在调用_lottery_winners_by_particients_and_ticket_counts()后,将不会使用参与者_和_ticket_counts。这就是为什么我可以把它打开。
我的解决方案是:
^{pr2}$
感谢大家的帮助!在