Packing code into functions

This commit is contained in:
User 2025-05-04 13:56:24 +03:00
parent a8e95bba21
commit 2a372c5d6f
1 changed files with 71 additions and 61 deletions

View File

@ -1,70 +1,80 @@
import datetime, random
import random
import datetime
from string import digits
def getBirthday(numberOfBerthday):
birthdays = []
for i in range(numberOfBerthday):
start_of_year = datetime.date(2000, 1, 1)
randomNumber_of_Days = datetime.timedelta(random.randint(1, 364))
birthday = start_of_year + randomNumber_of_Days
birthdays.append(birthday)
return birthdays
def getMatch(birthdays):
if len(birthdays) == len(set(birthdays)):
return None
for a, birthdayA in enumerate(birthdays):
for b, birthdayB in enumerate(birthdays[a + 1:]):
if birthdayA == birthdayB:
return birthdayA
# Создаем картеж
months = ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
matchs = ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec')
while True:
"""Ввод пользователя"""
print("How many birthdays shall i generate? (Max 100)")
"""Добавь потом в сам цикл while"""
responses = input("> ")
if responses.isdecimal() and (0 < int(responses) <= 100):
numBDay = int(responses)
break
print("Here are ", responses, " birthdays:")
birthdays = getBirthday(numBDay)
for i ,birthday in enumerate(birthdays):
if i != 0:
print(', ', end='')
montName = months[birthday.month - 1]
dateText = f"{montName} {birthday.day}"
print(dateText, end='')
def getBarthday(inp):
dates = []
for i in range(1, int(inp) + 1):
data = datetime.date(2000, 1, 1)
rand_days = datetime.timedelta(random.randint(1, 364))
rand_date = data + rand_days
dates.append(rand_date)
return dates
print()
match = getMatch(birthdays)
print("In this simulations, ", end='')
if match != None:
montName = months[match.month - 1]
dateText = f"{montName} {match.day}"
print(f'multiple peple have a birthday on {dateText}')
else:
print("There are no matching birthdays.")
print("Lets run anuther 100_000 simulater ")
simMatch = 0
for i in range(100_000):
if i % 10_000 == 0:
print(i , 'simulations run ...')
birthdays = getBirthday(numBDay)
if getMatch(birthdays) != None:
simMatch += 1
print("100_000 simulations run.")
probability = round((simMatch / 100_000) * 100, 2)
print(f"Out jf 100_000 simulations of {numBDay} peple, there was a\n"
f"matching birthday in tht group {simMatch} times. This means\n"
f"that {numBDay} peple have a {probability} % chanse jf\n"
"having a matching birthday in their group.\n")
def getMatch(list_date):
for a, barthdayA in enumerate(list_date):
for b, barthdayB in enumerate(list_date[a + 1:]):
if barthdayA == barthdayB:
return barthdayB
def numMatch(inp):
dates = getBarthday(inp)
for a, date in enumerate(dates):
if a != 0:
print(', ', end='')
barthday = matchs[date.month - 1]
print(f"{barthday} {date.day}", end='')
def sameMath(list_date):
if len(list_date) == len(set(list_date)):
print("\nNo such same birthday")
else:
same_math = getMatch(list_date)
barthday = matchs[same_math.month - 1]
print(f"\nRepeat date {barthday} {same_math.day}")
def simulations(inp):
digit = 0
for i in range(100_000):
dates = getBarthday(inp)
same_date = getMatch(dates)
if i % 10_000 == 0:
print(f"{i} simulations...")
if same_date != None:
digit += 1
number = round((digit / 100_000) * 100, 2)
print(f"Number same barthday = {digit}\n")
print(f"And chance same birhday = {number}")
def main():
while True:
print("Enter number no more than 100")
inp = ''
while not inp.isdecimal() or 0 > int(inp) > 100:
inp = input("> ")
list_date = getBarthday(inp)
numMatch(inp)
sameMath(list_date)
simulations(inp)
print("You want repeat?")
resp = input("(yes or no)> ")
if not resp.lower().startswith('y'):
print("Thanks for playing")
break
if __name__ == '__main__':
main()