Python練習題 046:Project Euler 019:每月1日是星期天

來源:互聯網
上載者:User

標籤: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日是星期天

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.