我遇到了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')
答案 0 :(得分: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))
答案 1 :(得分: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 :(得分:0)
true
答案 3 :(得分:0)
这是我写的方式。
# check probability for birthday reoccurance for a class of 23 students or the birthday paradox
import random as r
def check_date(students):
date=[]
count=0
for i in range(students): # Generate a random age for n students
date+=[r.randint(1,365)] # entire sample list for age is created
for letter in date: # check if the date repeats anywhere else
if date.count(letter)>=2: # Use count it's simple & easy.
count+=1
return count # count of a pair of students having same b.day
def simulations(s,students):
result=[] # empty list to update data.
simulation_match=0
for i in range(s):
result+=[check_date(students)] # get a sample list for all the students in 'n' no. of simulations
if check_date(students)>1: # if atleat 2 students have same b.day in each simulation
simulation_match+=1
return simulation_match,s,int(simulation_match/s*100),'%'
simulations(1000,23) # 1000 simulations with 23 students sample size
OUT:(494, 1000, 49, '%')
**百分比部分根据生成的随机int ****