zoukankan      html  css  js  c++  java
  • Python练习题 046:Project Euler 019:每月1日是星期天

    本题来自 Project Euler 第19题:https://projecteuler.net/problem=19

    '''
    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()直接判断是每月的第几天,倒是挺方便的~~~

  • 相关阅读:
    Python 函数装饰器简明教程
    *arg和**kwarg的区别
    克里金插值
    C语言Hello world
    ibatis错误
    typealias
    视图
    权限分级设置
    走出浮躁的泥沼:学会享受学习过程的乐趣
    R语言 eval(quote(x)) 和 eval(x)
  • 原文地址:https://www.cnblogs.com/iderek/p/6081576.html
Copyright © 2011-2022 走看看