python - 悖论python算法
问题描述
我正在尝试解决生日悖论问题的一个版本,其中我的概率为 0.5,但我需要找到至少 4 人在一周内过生日的人数 n。
我编写了能够模拟 2 个人在同一天过生日的代码。
import numpy
import matplotlib.pylab as plt
no_of_simulations = 1000
milestone_probabilities = [50, 75, 90, 99]
milestone_current = 0
def birthday_paradox(no_of_people, simulations):
global milestone_probabilities, milestone_current
same_birthday_four_people = 0
#We assume that there are 365 days in all years.
for sim in range(simulations):
birthdays = numpy.random.choice(365, no_of_people, replace=True)
unique_birthdays = set(birthdays)
if len(unique_birthdays) < no_of_people:
same_birthday_four_people += 1
success_fraction = same_birthday_four_people/simulations
if milestone_current < len(milestone_probabilities) and success_fraction*100 > milestone_probabilities[milestone_current]:
print("P(Four people sharing birthday in a room with " + str(no_of_people) + " people) = " + str(success_fraction))
milestone_current += 1
return success_fraction
def main():
day = []
success = []
for i in range(1, 366): #Executing for all possible cases where can have unique birthdays, i.e. from 1 person to a maximum of 365 people in a room
day.append(i)
success.append(birthday_paradox(i, no_of_simulations))
plt.plot(day, success)
plt.show()
main()
我正在寻找修改代码以查找 4 组而不是 2 组,然后计算它们之间的差异小于等于 7 以满足问题。
我是走在正确的道路上还是应该以不同的方式解决这个问题?
解决方案
您的算法的关键部分在于以下几行:
unique_birthdays = set(birthdays)
if len(unique_birthdays) < no_of_people:
same_birthday_four_people += 1
当您测试两个不同的人是否有相同的生日时,将唯一生日的数量与完成工作的人数进行比较,但它不适用于您的新测试。
定义一个新函数,它将接收生日数组并在检查是否确实有 4 个不同的人在 7 天的范围内过生日后返回True
或返回:False
def four_birthdays_same_week(birthdays):
# fill this function code
def birthday_paradox(no_of_people, simulations):
...
(这个函数可以在birthday_paradox
函数外定义)
然后切换这段代码:
if len(unique_birthdays) < no_of_people:
same_birthday_four_people += 1
进入:
if four_birthdays_same_week(birthdays):
same_birthday_four_people += 1
关于检查同一周是否有 4 个不同生日的算法:一个基本的想法是对生日数组进行排序,然后对于每组 4 个生日检查它们之间的日期范围是否等于或小于 7:
如果它也就是说,函数可以立即返回True
。(我相信这个算法可以大大改进。)
如果扫描整个数组后我们没有返回True
,函数可以返回False
。
推荐阅读
- java - 当我从 Eclipse 运行我的 TestNG xml 文件时,当我从命令提示符运行它时它运行良好
- ruby - 用户和团队——多对多关系 Ruby
- php - 在由 Wordpress 提供支持的网站上,PHP 代码在按下提交按钮后不会发送电子邮件
- javascript - 使用 d3.stack() 函数的 D3 堆积条形图
- mysql - 带有 powershell 的 SQL 备份自动化
- java - r8.jar 位于 Android SDK 的什么位置?
- angular - Angular 6 库 - 导入模块问题
- c# - 为什么只有 C# 应用程序需要 BStrWrapper?
- android - ScrollView 填满整个屏幕
- xcode - 重命名用户文件夹后 Xcode 存档错误