生日悖论 python程序

题目

生日悖论分析。生日悖论指如果一个房间里有23人或以上,那么至少有两个人生日相同的概率大于50%。编写程序,输出在不同随机样本数量下,23个人中至少两个人生日相同的概率。

程序(python)

#生日悖论分析
#通过集合的无重复性来判断生日是否有重复的
# persons:班级的人数
# counts: 中间计数器,有重复生日的次数
# stop: 实验的总次数
# birthdays: 班级中每个人的生日
import random

persons = 23
counts = 0
stop = 10000

for i in range(1, stop+1):
    birthdays = []
    for i in range(persons):
        n = random.randint(1, 365)
        birthdays.append(n)
    length1 = len(birthdays)#其实就是persons
    length2 = len(set(birthdays))
    if length1 != length2:
        counts = counts +1

print(f'{persons}人中至少两个人生日相同的概率是{counts/stop*100:.2f}%')

程序解析

(1)

    birthdays = []
    for i in range(persons):
        n = random.randint(1, 365)
        birthdays.append(n)

随机产生23个人的生日。假设一年为365天,生日用1到365共计365个整数代替。

(2)

    length1 = len(birthdays)#其实就是persons
    length2 = len(set(birthdays))

length1 代表刚才产生生日列表的长度,其实就是persons参数的大小。
length2 由于python中集合中元素不可重复,通过set处理birthdays列表(就是将列表变成集合),就会去除重复元素并返回一个没有顺序的集合。

(3)

    if length1 != length2:
        counts = counts +1

如果length1和length2数值不一样,说明该班级有生日重复的人,计数器counts加1.。

(4)

print(f'{persons}人中至少两个人生日相同的概率是{counts/stop*100:.2f}%')

计数器counts与实验次数stop的比值就是所求概率。

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐