Topic from Project Euler 19th: https://projecteuler.net/problem=19
"How many Sundays fell on the first of the Monthduring the Twentieth Century (1 Jan 1901 to 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 # Number of Sunday while Firstsunday <= lastday: if Firstsunday.day = = 1: #若为每月的1日 Sundaycount + = 1 firstsunday + = Delta7 #7天7天递增print (sundaycount)
Well, Euler plan 18th do not come out, skip first, do the 19th question first.
This idea is very simple: within the interval, first find out the 1th Sunday, and then 7 days 7 days to find, as long as the 1th day of the month, the counter will add 1, soon there is an answer.
In other words, Python does not seem to be like MySQL, just take a date with the number n, calculate the date after n days, but with the help of Timedelta, set the interval time, then perform the operation, feel ... It's kind of troublesome. However, it is very convenient to judge the day of the Week with Isoweekday () directly, and to judge the number of days in a month.
Python exercises 046:project Euler 019:1st per month is Sunday