首页 > 解决方案 > 悖论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 以满足问题。

我是走在正确的道路上还是应该以不同的方式解决这个问题?

标签: python

解决方案


您的算法的关键部分在于以下几行:

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


推荐阅读