update birthdayparadox.py
This commit is contained in:
parent
210cf4418c
commit
74ceea588a
@ -6,6 +6,7 @@ Tags: short, math, simulation"""
|
|||||||
|
|
||||||
import datetime, random
|
import datetime, random
|
||||||
|
|
||||||
|
|
||||||
def getBirthdays(numberOfBirthdays):
|
def getBirthdays(numberOfBirthdays):
|
||||||
"""Returns a list of number random date objects for birthdays."""
|
"""Returns a list of number random date objects for birthdays."""
|
||||||
birthdays = []
|
birthdays = []
|
||||||
@ -20,4 +21,49 @@ def getBirthdays(numberOfBirthdays):
|
|||||||
birthdays.append(birthday)
|
birthdays.append(birthday)
|
||||||
return birthdays
|
return birthdays
|
||||||
|
|
||||||
|
def getMatch(birthdays):
|
||||||
|
"""Returns the date object of a birthday that occurs more than once
|
||||||
|
in the birthdays list."""
|
||||||
|
if len(birthdays) == len(set(birthdays)):
|
||||||
|
return None #All birthdays are unique, so return None.
|
||||||
|
|
||||||
|
# Compare each birthday to every other birthday:
|
||||||
|
for a, birthdayA in enumerate(birthdays):
|
||||||
|
for b, birthdayB in enumerate(birthdays[a + 1 :]):
|
||||||
|
if birthdayA == birthdayB:
|
||||||
|
return birthdayA # Return the matching birthday
|
||||||
|
|
||||||
|
# Display the intro:
|
||||||
|
print('''Birthday Paradox, by Al Sweigart al@inventwithpython.com
|
||||||
|
The Birthday Paradox shows us that in a group of N people, the odds
|
||||||
|
that two of them have matching birthdays is surprisingly large.
|
||||||
|
This program does a Monte Carlo simulation (that is, repeated random
|
||||||
|
simulations) to explore this concept.
|
||||||
|
|
||||||
|
(It's not actually a paradox, it's just a surprising result.)
|
||||||
|
''')
|
||||||
|
# Set up a tuple of month names in order:
|
||||||
|
MONTHS = ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
|
||||||
|
'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec')
|
||||||
|
|
||||||
|
while True: # Keep asking until the user enters a valid amount.
|
||||||
|
print('How many birthdays shall I generate (Max 100)')
|
||||||
|
response = input('> ')
|
||||||
|
if response.isdecimal() and (0 < int(response) <= 100):
|
||||||
|
numBDays = int(response)
|
||||||
|
break # User has entered a valid amount
|
||||||
|
print()
|
||||||
|
|
||||||
|
# Generate and display birthdays:
|
||||||
|
print('Here are', numBDays, 'birthdays:')
|
||||||
|
birthdays = getBirthdays(numBDays)
|
||||||
|
for i, birthday in enumerate(birthdays):
|
||||||
|
if i != 0:
|
||||||
|
# Display a comma for each birthday after the first birthday.
|
||||||
|
print(', ', end='')
|
||||||
|
monthName = MONTHS[birthday.month - 1]
|
||||||
|
dateText = '{} {}'.format(monthName, match.day)
|
||||||
|
print(dateText, end='')
|
||||||
|
print()
|
||||||
|
print()
|
||||||
|
|
||||||
Loading…
x
Reference in New Issue
Block a user