python彩票模型_什么是Python式的彩票经营方式?

我需要从加权集合中随机选取几个项目。重量较大的物品更容易被挑选。我决定在抽签后做这个模型。我觉得我的解决方案是很好的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}$

感谢大家的帮助!在

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值