Project Euler 19 Counting Sundays

Question

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

Analysis

  1. 闰年影响到二月的天数,闰年的判断可以用函数实现。
  2. 星期天的判断方法就是所要求的日期距1900.1.1的天数对7取余。

Program

def isLeapYear(year):
    if (year % 400 == 0):
        return True
    elif (year % 100 == 0):
        return False
    elif (year % 4 == 0):
        return True
    else:
        return False


def isSunday(day):
    if (day % 7 == 6):
        return True
    else:
        return False


days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
num_sundays = 0
index = sum(days)
if (isLeapYear(1900)):
    index += 1

for year in range(1901, 2001):
    if (isLeapYear(year)):
        days[1] = 29
    else:
        days[1] = 28

    for mouth in range(12):
        if (isSunday(index)):
            num_sundays += 1
        index += days[mouth]

print(num_sundays)

你可能感兴趣的:(Project Euler 19 Counting Sundays)