2017-10-12 1133 views
0

我在編程時遇到了Python中生日悖論的問題。生日悖論基本上說,如果一個班有23個人,那麼他們中的兩個將有相同的生日的概率是50%。生日悖論python - 不正確的概率輸出

我試圖在Python中對這個悖論進行編碼,但它不斷回來的概率接近25%。我對Python非常陌生,所以毫無疑問,這個問題有一個簡單的解決方案。這裏是我的代碼:

import random 


def random_birthdays(): 
    bdays = [] 
    bdays = [random.randint(1, 365) for i in range(23)] 
    bdays.sort() 
    for x in bdays: 
     while x < len(bdays)-1: 
      if bdays[x] == bdays[x+1]: 
       print(bdays[x]) 
       return True 
      x+=1 
     return False 

count = 0 
for i in range (1000): 
if random_birthdays() == True: 
    count = count + 1 


print('In a sample of 1000 classes each with 23 pupils, there were', count, 'classes with individuals with the same birthday') 
+3

你做了什麼樣的調試?要求我們全面調試您的代碼並不合適。 – Carcigenicate

+1

第二個問題的答案是單一責任原則。 – jonrsharpe

回答

1

錯誤在這行:

for x in bdays: 

應該

for x in range(len(bdays)): 

因爲你需要遍歷生日的指標,但不是生日本身。

還有一個優化:

count = 0 
for i in range (1000): 
    if random_birthdays() == True: 
     count = count + 1 

可以通過

count = sum(random_birthdays() for _ in range(1000)) 
2

除了更換,你的函數應該實現這樣的:

import random 

def random_birthdays(pupils): 
    bdays = [random.randint(1, 365) for _ in range(pupils)] 
    return pupils > len(set(bdays)) 

這消除了這麼多的來源錯誤。

這可以被稱爲@Zefick表明:

count = sum(random_birthdays(23) for _ in range(1000))