首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Python-100 练习题 04 判断天数

Python-100 练习题 04 判断天数

作者头像
kbsc13
发布2019-08-16 14:37:18
8050
发布2019-08-16 14:37:18
举报
文章被收录于专栏:AI 算法笔记AI 算法笔记

2019年第 18 篇文章,总第 42 篇文章 本文大约 1300 字,阅读大约需要 6 分钟

练习题 4 的网址:

http://www.runoob.com/python/python-exercise-example4.html


Example-4 判断天数

题目:输入某年某月某日,判断这一天是这一年的第几天?

思路

判断输入的日期是一年中的第几天,因为一年有12个月,我们可以先考虑计算逐月累计的天数,假设输入的月份是 m,那么前 m-1个月份的天数是可以计算出来的,比如输入的是 2018 年 3 月 5 日,那么前两个月的天数就是31+28=59天,然后再加上输入的天,即 59+5=64天。

当然,涉及到日期,年份,都需要考虑闰年,闰年的定义如下,来自百度百科

普通闰年: 能被4整除但不能被100整除的年份为普通闰年。(如2004年就是闰年,1999年不是闰年); 世纪闰年: 能被400整除的为世纪闰年。(如2000年是世纪闰年,1900年不是世纪闰年);

代码实现

实现的代码如下:

def calculate_days():
    year = int(input('year:\n'))
    month = int(input('month:\n'))
    day = int(input('day:\n'))

    # 统计前 m-1 个月的天数
    months = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334]
    sums = 0
    if 0 < month <= 12:
        sums = months[month - 1]
    else:
        print('Invalid month:', month)

    sums += day

    # 判断闰年
    is_leap = False
    if (year % 400 == 0) or ((year % 4 == 0) and (year % 100 != 0)):
        is_leap = True
    if is_leap and month > 2:
        sums += 1
    return sums

测试例子如下,给出两个同样的日期,但年份不同,闰年的 2016 年和非闰年的 2018年。

# 非闰年
year:
2018
month:
3
day:
5
it is the 64th day

# 闰年
year:
2016
month:
3
day:
5
it is the 65th day

源代码在:

https://github.com/ccc013/CodesNotes/blob/master/Python_100_examples/example4.py

或者点击原文,也可以查看源代码。

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2019-02-18,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 算法猿的成长 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Example-4 判断天数
    • 思路
      • 代码实现
      领券
      问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档