CMU Coding Bootcamp
1def is_leap_year(yyyy: int) -> bool:
2 return not (yyyy % 4 or (yyyy % 400 and not yyyy % 100))
3
4
5def sum_months(mm: int, yyyy: int) -> int:
6 months = [
7 31,
8 29 if is_leap_year(yyyy) else 28,
9 31,
10 30,
11 31,
12 30,
13 31,
14 31,
15 30,
16 31,
17 30,
18 31,
19 ]
20 return sum(months[:mm])
21
22
23def nth_day(s: str) -> int:
24 """Calculate the nth day since the beginning of the year."""
25 mm, dd, yyyy = map(int, [s[:2], s[2:4], s[4:]])
26 day_since_new_year = dd + sum_months(mm - 1, yyyy)
27 return yyyy * 1000 + day_since_new_year
28
29
30print("we're testing the nth day function...", end="")
31assert nth_day("02072016") == 2016038
32assert nth_day("12201996") == 1996355
33# assert(nth_day("abcdef") == None)
34assert nth_day("12312020") == 2020366
35assert nth_day("12312021") == 2021365
36print("and it passes the example cases")