-1

我需要这段代码来输出匹配生日的总数,但计数一直在增长,我不知道为什么。我们应该期望看到总数约为。模拟量的一半。我现在将它附加到一个列表中,以可视化计数的变化。

import random
birthmonth = []
birthday= []
def birthday_paradox():
    """
    
    """
    months31 = (1,3,5,7,8,10,12)
    months30 = (4,6,9,11)
    day31 = random.randint(1,31)
    day30 = random.randint(1,30)
    day29 = random.randint(1,29)
    month = random.randint(1,12)
    
    for i in months31:
        if month == i:
            birthmonth.append(month)
            birthday.append(day31)
    for i in months30:
        if month == i:
            birthmonth.append(month)
            birthday.append(day30)
    if month == 2:
        birthmonth.append(month)
        birthday.append(day29)

def frequency_of_matches(number_of_people:int = 23):
    """
    
    """
    count = 0
    for i in range(number_of_people):
        birthday_paradox()
    sorted_birthday_list = sorted(list(zip(birthmonth, birthday))) 
    
    for i in range(len(sorted_birthday_list)):
        if sorted_birthday_list[i] == sorted_birthday_list[i - 1]:
            count += 1
    return count
       
    
def simulations(number_of_simulations:int = 100):
    total = []
    for i in range(number_of_simulations):
        total.append(frequency_of_matches())
    return total


simulations(25)

示例输出:

[1, 3, 7, 9, 13, 23, 28, 42, 51, 61, 70, 84, 97, 112, 124, 138, 153, 163, 178, 196, 213, 228, 244, 261, 277]
4

1 回答 1

0

根本问题是您的birthmonthbirthday列表不断增长和增长。你永远不会清除它们。这就是为什么你的设计——修改全局变量——是一个糟糕的设计。该函数应该重新开始并返回其输出。全球人是邪恶的。

此外,您选择随机生日的方法很疯狂。这是一个只需要一个随机数的替换,并且只使用一个全局变量,它是一个常量。

import random
import datetime

jan1 = datetime.datetime(2022,1,1)

def birthday_paradox():
    base = jan1 + datetime.timedelta(days=random.randint(0,364))
    return base.month,base.day

def frequency_of_matches(number_of_people:int = 23):
    birthdays = [birthday_paradox() for i in range(number_of_people)]
    birthdays.sort()
    
    count = 0
    for i in range(len(birthdays)-1):
        if birthdays[i] == birthdays[i+1]:
            count += 1
    return count
       
def simulations(number_of_simulations:int = 100):
    total = []
    for i in range(number_of_simulations):
        total.append(frequency_of_matches())
    return total

print(simulations(25))

如果您真的非常担心这里缺少 2 月 29 日,请更改为:

    base = jan1 + datetime.timedelta(days=random.randint(0,365*4+1))
于 2022-02-13T01:46:02.913 回答