Created
November 5, 2019 13:03
-
-
Save voith/b3ea31c8f749f739521b3ba10d3c6f36 to your computer and use it in GitHub Desktop.
Calculate number of Sundays that fell on the first of the month during the twentieth century.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def check_if_leap_year(year: int) -> bool: | |
if ( | |
year % 4 == 0 and year % 100 != 0 | |
) or ( | |
year % 400 == 0 | |
): | |
return True | |
else: | |
return False | |
def get_days_in_month(month: int, year: int) -> int: | |
no_days_in_month = [ | |
31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 | |
] | |
days_to_increment = 0 | |
if check_if_leap_year(year) and month == 2: | |
days_to_increment = 1 | |
return no_days_in_month[month - 1] + days_to_increment | |
# track days of week as an integer | |
# 0 Sun | |
# 1 Mon | |
# 2 Tue | |
# 3 Wed | |
# 4 Thu | |
# 5 Fri | |
# 6 Sat | |
# starting day: 1 Jan 1901 was a tuesday | |
day_of_week = 2 | |
count_sunday = 0 | |
for year in range(1901, 2000 + 1): | |
for month in range(1, 12 + 1): | |
days_in_month = get_days_in_month(month, year) + 1 # + 1 for calculating start of next month | |
# calculate day of week for start of every month | |
day_of_week = (day_of_week + days_in_month % 7 + 7 * int(days_in_month % 7 == 0) - 1) % 7 | |
if day_of_week == 0: # if sunday | |
count_sunday += 1 | |
print(count_sunday) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment