Problem 19: Counting Sundays
You are given the following information, but you may prefer to do some research for yourself.
- 1 Jan 1900 was a Monday.
- Thirty days has September,
April, June and November.
All the rest have thirty-one,
Saving February alone,
Which has twenty-eight, rain or shine.
And on leap years, twenty-nine. - A leap year occurs on any year evenly divisible by 4, but not on a century unless it is divisible by 400.
How many Sundays fell on the first of the month during the twentieth century (1 Jan 1901 to 31 Dec 2000)?
weekday = ('Sunday', 'Monday', 'Tuesday', 'Wednesday',
'Thursday', 'Friday', 'Saturday')
months = ('January', 'February', 'March', 'April', 'May', 'June', 'July',
'August', 'September', 'October', 'November', 'December')
days = {'January': 31,
'February': 28,
'March': 31,
'April': 30,
'May': 31,
'June': 30,
'July': 31,
'August': 31,
'September': 30,
'October': 31,
'November': 30,
'December': 31}
# Algorithm:
# Weekdays always follow 1-7 pattern
# Months always follow 1-12, only number of days varies, and only in Feb
def leap_year(n):
"""Return whether provided year is a leap year"""
if n % 4 == 0:
if n % 100 == 0:
if n % 400 ==0:
return True
return False
return True
return False
def main():
w = 2 #January 1st, 1901 was a Tuesday
first_sundays = 0
for year in range(1901, 2001):
#print(f"{year}: {leap_year(year)}")
#days_in_year = 0
for month in months:
if month == 'February' and leap_year(year):
upper = 30
else:
upper = days[month]+1
for day in range(1, upper):
#print(f"{month} {day} {year}: {weekday[w]}")
#days_in_year += 1
if day == 1 and weekday[w] == 'Sunday':
first_sundays += 1
w = (w + 1) % 7
print(first_sundays)
main()
Click to reveal output
171