Python exercises 046:project Euler 019:1st per month is Sunday

Source: Internet
Author: User
Tags timedelta

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.