题目

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

解答

首先需要定义一个函数,给个年份,输出一年中每月的天数:

def get_days(year):  
    days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]  
    if year % 100 == 0 and year % 400 == 0:  
        leap = 1  
    elif year % 100 != 0 and year % 4 == 0:  
        leap = 1  
    else:  
        leap = 0  
    days[1] += leap  
    return days

已知起点是1900-01-01是星期一,但我们的起点是1901-01-01,所以需要算一下,这一年过后是星期几,当然要算100年,每一年的1月1号是星期几都得知道,这样才好解题。无非是每月累加起来,模7,然后看月底最后一天是不是周六,因为是的话,则下个月的第一天是周日。就能够计数。

import numpy as np  
def solution19():  
    start = sum(get_days(1900)) % 7  
      
    cnt = 0  
    for year in range(1901, 2001):  
        x = (np.cumsum(np.array(get_days(1901))) + start) % 7  
        cnt += np.sum(x == 6)  
        start = x[-1]  
    return cnt