標籤:sql cte bre get port 遞增 https target 歐拉
本題來自 Project Euler 第19題:https://projecteuler.net/problem=19
‘‘‘How many Sundays fell on the first of the monthduring 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 += delta1delta7 = 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()直接判斷是每月的第幾天,倒是挺方便的~~~
Python練習題 046:Project Euler 019:每月1日是星期天