我正试图让它正确地执行生日悖论,并已将其压缩以希望在固定状态下有意义。我相信我知道我的错误在哪里,但我不太确定我该如何解决它们。我删除了许多循环和打印语句,希望能理解我正在尝试做的事情。当我使用以下代码运行它时,它会执行一些操作,但我需要它通过用户输入以及特定输入的正确操作次数来执行它
# Birthday Paradox Program
import random
import datetime
matchedBirthdays = []
theBirthdays = []
# Generate birthdays
def generateBirthdays(numBirthdays):
for i in range(numBirthdays):
x = datetime.datetime.now()
presentYear = x.year
year = random.randint(1900, presentYear)
month = random.randint(1, 12)
if month == 2:
day = random.randint(1, 28)
elif month % 2 == 1 and month <= 7:
day = random.randint(1, 31)
else:
day = random.randint(1, 30)
x = datetime.datetime(year, month, day)
birthday = x.strftime("%b") + " " + x.strftime("%d")
theBirthdays.append(birthday)
return theBirthdays
def matchBirthday(theBirthdays):
global matchedBirthdays
count = 0
for i in range(len(theBirthdays)):
if theBirthdays.count(theBirthdays[i]) > 1 and matchedBirthdays.__contains__(theBirthdays[i]) == False:
matchedBirthdays.append(theBirthdays[i])
else:
continue
count = len(matchedBirthdays)
return count
numBirthdays = 8
theBirthdays = generateBirthdays(numBirthdays)
# numBirthdays = int(input("How many birthdays shall I generate? (Max 100)\n"))
# Check user input
# Generate birthdays
# Print out each birthday
print("Here are " + str(numBirthdays) + " birthdays:")
matchedBirthdays = []
print("Generating " + str(numBirthdays) + " random birthdays 100,000 times...")
sum = 0
for i in range(11):
theBirthdays = generateBirthdays(numBirthdays)
sum += matchBirthday(theBirthdays)
chance = round((sum / 100000) * 100, 2)
print("Out of 100,000 simulations of " + str(numBirthdays) + " people, there was a matching birthday in that group " + str(sum) + " times. This means that " + str(numBirthdays) + " people have a " + str(chance) + "% "
"chance of having a matching\n birthday in their group.")