'''
How many Sundays fell on the first of the month
during the twentieth century (1 Jan 1901 to 31 Dec 2000)?
Answer: 171
'''
from datetime import *
firstDay = date(1901,1,1)
lastDay = date(2000,12,31)
delta1 = timedelta(days=1)
firstSunday = date(1900,1,1)
while firstSunday == date(1900,1,1):
if firstDay.isoweekday() == 7:
firstSunday = firstDay #找出第1个星期天
break
else:
firstDay += delta1
delta7 = timedelta(days=7)
sundayCount = 0 #星期天的数量
while firstSunday <= lastDay:
if firstSunday.day == 1: #若为每月的1日
sundayCount += 1
firstSunday += delta7 #7天7天递增
print(sundayCount)
好吧,欧拉计划第18题做不出来,先跳过,先做第19题吧。
这题思路挺简单:在区间之内,先找出第1个星期天,然后7天7天地找,只要是每月的第1天,计数器就加1,很快就有答案。
话说,Python好像不能像MySQL那样,直接拿一个日期加上数字n,计算n天之后的日期;而是得借助timedelta,设定间隔时间,再进行运算,感觉……挺麻烦的。不过,用isoweekday()直接判断星期几、用day()直接判断是每月的第几天,倒是挺方便的~~~