Skip to content

Instantly share code, notes, and snippets.

@JosephTLyons
Last active July 4, 2021 02:55
Show Gist options
  • Select an option

  • Save JosephTLyons/1f8e73e9df441edea5f4a9426468fe71 to your computer and use it in GitHub Desktop.

Select an option

Save JosephTLyons/1f8e73e9df441edea5f4a9426468fe71 to your computer and use it in GitHub Desktop.
Playing around with the Birthday Paradox
import random
from datetime import datetime, timedelta
def convert_integer_to_date(day_number_offset):
beginning_of_year = datetime(year=2021, month=1, day=1)
date = beginning_of_year + timedelta(days=day_number_offset)
date_string = date.strftime("%B %d")
return date_string
def birthday_paradox(number_of_birthdays):
birthdays = sorted([random.randint(0, 364) for _ in range(number_of_birthdays)])
unique_birthdays = set()
matching_birthdays = []
for birthday in birthdays:
if birthday in unique_birthdays:
matching_birthdays.append(convert_integer_to_date(birthday))
else:
unique_birthdays.add(birthday)
return list(set(matching_birthdays))
def main():
for i in range(2, 102):
number_of_matches = 0
number_of_runs = 1_000
for j in range(number_of_runs):
matching_birthdays = birthday_paradox(i)
# print(f"{j}: {matching_birthdays}")
if matching_birthdays:
number_of_matches += 1
match_percentage = round((number_of_matches / number_of_runs) * 100, 2)
# print()
print(f"Number of Birthdays: {i}) - {match_percentage}%")
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment