2012-12-24 121 views
1

我正在研究一個代碼來解決這個問題:彩票概率Python代碼

你和你的朋友都在紐約,並打算去看百老匯音樂劇。不幸的是,紐約是紐約,門票只是一點點貴。但是其中一個節目每晚都有票券抽獎,在這些抽獎人羣中,有機會贏得購買價格稍低的優惠票的機會。彩票的操作如下。首先,每個人都有興趣進入彩票。然後,n個幸運獲勝者被抽出,並且每個人都被提供購買高達t票。

鑑於你組(所有進入彩票)的形式進入彩票的人總數M在人們數p,那是什麼,你將能夠獲得門票爲您的整個組的概率是多少?假設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.我真的很感激,如果任何人都可以幫助我在這裏。

+1

你應該看看'itertools.combinations' – jdotjdot

+0

整數除法.... –

+0

@LongPham可以更具體地說明「我認爲itertools不適用於整數除法」是什麼意思?有關'itertools.combinations()'的評論並不是指與劃分有關的任何內容。 – Matt

回答

5

在Python 2中,當你劃分兩個整數時,你總會得到一個整數結果。嘗試添加此行到文件的頂部,這將讓你在新的Python 3的行爲,其中將整型產生浮動:

from __future__ import division 
+0

是的,它的工作!非常感謝你! –

+0

@LongPham如果有效,請務必接受Ned的回答,以便問題被標記爲已解決! –