Problem 19

Problem 19

You are given the following information, but you may prefer to do some research for yourself.
以下信息仅供参考(你可能会想自己去百度):
1 Jan 1900 was a Monday.  1900年一月一号是星期一
Thirty days has September, 九月、四月、六月以及十一月有30天
April, June and November.
All the rest have thirty-one, 其他月份有31天
Saving February alone, 二月份比较特殊
Which has twenty-eight, rain or shine. 闰年29天,平年28天
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.
闰年指可以被4整除的年份,但如果是世纪(如:1900)的话,需要能够整除400才算闰年
How many Sundays fell on the first of the month during the twentieth century (1 Jan 1901 to 31 Dec 2000)?
二十世纪有多少个星期天在月份的第一天(从1901-01-01到2000-12-31)?
def leep_year(year):
    if year % 100 == 0:  # century
        if year % 400 == 0:
            return True
    else:
        if year % 4 == 0:
            return True
    return False


week = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
month = {'January': 31, 'February': 28, 'March': 31, 'April': 30, 'May': 31, 'June': 30,
         'July': 31, 'August': 31, 'September': 30, 'October': 31, 'November': 30, 'December': 31}

count = 0
day = 'Monday'  # 1900-01-01是星期一
index = 0
for year in range(1900, 2001):
    if leep_year(year):  # 闰年
        month['February'] = 29
    else:  # 平年
        month['February'] = 28
    for m, d in month.items():
        if day == 'Sunday':
            count += 1
        index = week.index(day) + d % 7
        if index >= 7:
            index %= 7
        day = week[index]
    if year == 1900:  # 如果是1900年,归零(从1901-01-01到2000-12-31)
        count = 0
print(count)


Resistance is Futile!
原文地址:https://www.cnblogs.com/noonjuan/p/11028852.html