我正在编写一个代码来解决这个问题:
你和你的朋友在纽约,打算去看一场百老汇音乐剧。不幸的是,纽约就是纽约,门票只是有点贵。但其中一场演出每晚都有彩票抽奖,像你这样贫困的人有机会中奖,买到稍微便宜一点的好座位的门票。彩票的操作如下。首先,每个感兴趣的人都可以参加抽奖。然后,抽出n个幸运的中奖者,每个人都可以购买最多t张彩票。
给定你的小组中的人数p(所有人都参加了抽奖)和参加抽奖的总人数m,你能够获得整个小组的彩票的概率是多少?假设n个幸运的中奖者是从参加抽奖的m个人中均匀随机选出的,每个人最多只能中奖一次。
下面是我的代码:
import math
def lottery():
m = int(raw_input('The number of people who entered the lottery: '))
n = int(raw_input('The number of winner drawn from the total: '))
t = int(raw_input('The number of tickets each winner can purchase: '))
p = int(raw_input('The number of people in your group: '))
def combinations(n, k):
if 0 <= k <= n:
ntok = 1
ktok = 1
for t in xrange(1, min(k, n - k) + 1):
ntok *= n
ktok *= t
n -= 1
return ntok // ktok
else:
return 0
needed_wins = int(math.ceil(p/t))
others = m - p
loss = 0
for i in range(needed_wins):
loss += combinations(others, n-i) * combinations(p, i)
total = combinations(m, n)
prob = 1 - loss / total
print(prob)我试着运行它,但是结果是错误的。例如,如果组合是(100,10,2, 1 ),结果应该是0.1;相反,它返回1。如果有人能在这里帮助我,我真的很感激。
发布于 2012-12-24 10:35:52
在Python 2中,当您将两个整数相除时,总是得到一个整数结果。尝试将下面这一行添加到文件的顶部,这将使您获得新的Python 3行为,其中除以int将生成浮点数:
from __future__ import divisionhttps://stackoverflow.com/questions/14016409
复制相似问题