我在用 Python 编写生日悖论时遇到问题。生日悖论基本上是说,如果一个班有 23 个人,那么他们两个生日相同的概率是 50%。
我试图用 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')