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)?


Idea

Accumulate the total days of each month since 1 Jan 1900, and check if the first day of this month is sunday.


In [1]:
month_day_norm = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
month_day_leap = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
In [2]:
def is_leap(y):
    return y % 400 == 0 or (y % 100 != 0 and y % 4 == 0)
In [3]:
is_leap(1901), is_leap(1904), is_leap(2000), is_leap(1900)
Out[3]:
(False, True, True, False)
In [4]:
def solve():
    day_cnt = 0
    sunday_first_cnt = 0
    for y in range(1900, 2001):
        if is_leap(y):
            month_day = month_day_leap
        else:
            month_day = month_day_norm
            
        for m in range(12):
            if y != 1900 and day_cnt % 7 == 6:
                sunday_first_cnt += 1
            day_cnt += month_day[m]
    return sunday_first_cnt
In [5]:
solve()
Out[5]:
171