Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
Calculate two year's worth of birthdays solution in Clear category for Next Birthday by kkkkk
from typing import Dict, Tuple
from calendar import isleap
from datetime import date
Date = Tuple[int, int, int]
def next_birthday(today: Date, birthdates: Dict[str, Date]) -> \
Tuple[int, Dict[str, int]]:
"""For upcoming closest bday, return days to bday and persons with bday."""
todays_date = date(*today)
todays_year = todays_date.year
# Calculate birthdays coming up this year and for the next. Depending
# on "today"s date, some birthdays may fall in the next year.
bdays = {todays_year: {}, todays_year+1: {}}
for person, birthdate in birthdates.items():
for year in bdays:
# If the birthdate is 2/29 and "today" is not in a leap year,
# switch, the birthdate to 3/1.
_, month, day = birthdate
if month == 2 and day == 29 and not isleap(year):
month, day = 3, 1
# Calculate the number of days between the birthdate and the
# given date of today. Only save upcoming birthdays.
days_till_bday = date(year, month, day) - todays_date
if days_till_bday.days >= 0:
bdays[year][person] = days_till_bday.days
# If there are birthdays for "today"s year, that's the year we'll
# use because they'll come sooner than next year's.
if not bdays[todays_date.year]:
todays_year = todays_date.year + 1
# Find the closest birthday, then all the people with that birthday.
closest_day = min(bdays[todays_year].values())
bday_persons = {}
for person, days in bdays[todays_year].items():
if days == closest_day:
bday_persons[person] = (todays_year - birthdates[person][0])
return (closest_day, bday_persons)
Sept. 15, 2020
Comments: