Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
calendar.isleap(year) with explanations solution in Clear category for Next Birthday by Oksana_Antropova
from typing import Dict, Tuple
from datetime import date
import calendar
Date = Tuple[int, int, int]
def leap_date(year: int, month: int, day: int) -> date:
""""
Changes February 29th for March 1st if the year is common
"""
if (month, day) == (2, 29) and not calendar.isleap(year):
month, day = 3, 1
return date(year, month, day)
def next_celebration(today: date, born: date) -> date:
"""
Finds the date of next celebration:
- processes the leap dates;
- if the celebration this year has already passed adds one to the year of next celebration
"""
born = leap_date(today.year, born.month, born.day)
year = today.year + ((born.month, born.day) < (today.month, today.day))
return leap_date(year, born.month, born.day)
def next_birthday(today: Date, birthdates: Dict[str, Date]) -> Tuple[int, Dict[str, int]]:
today = date(*today)
next_celebrations = {name : next_celebration(today, date(*birthday))
for name, birthday in birthdates.items()}
nearest_celebration = min(next_celebrations.values())
diff = (nearest_celebration - today).days
return (diff, {name : date.year - birthdates[name][0]
for name, date in next_celebrations.items() if date == nearest_celebration})
Oct. 11, 2020