第四题

Posted lovely-bones

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了第四题相关的知识,希望对你有一定的参考价值。

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

自己的代码如下:

 1 # -*- coding: utf-8 -*-
 2 """
 3 Created on Fri Oct  4 22:08:42 2019
 4 
 5 @author: Franz
 6 """
 7 
 8 def leap(year):
 9     index = False
10     if year % 400 == 0:
11         index = True
12     else:
13         if year % 4 == 0 and year % 100 !=0:
14             index = True
15     return index
16 
17 year = int(input(please input the year you want to check: ));
18 month = int(input(please input the month you want to check: ));
19 day = int(input(please input the day you want to check: ))
20 
21 mon_days = [0,31,59,90,120,151,181,212,243,273,304,334];
22 if not leap(year):
23     days = mon_days[month-1]+day;
24 else:
25     if month >= 2:
26         days = month_days[month-1]+1+day
27     else:
28         days = mon_days[month-1]+day;
29 
30 print(it is the %dth day. % days)

分析:代码写的很渣,其中很多条件判断可以合到一个if语句中进行判断,对于代码优先级还欠考虑。优点在于领悟到了闰年月份与非闰年月份天数的差异,并根据一个数组实现月份的查询。

如下是标准答案(python-2.7x)。

#!/usr/bin/python
# -*- coding: UTF-8 -*-
 
year = int(raw_input(‘year:\n‘))
month = int(raw_input(‘month:\n‘))
day = int(raw_input(‘day:\n‘))
 
months = (0,31,59,90,120,151,181,212,243,273,304,334)
if 0 < month <= 12:
    sum = months[month - 1]
else:
    print ‘data error‘
sum += day
leap = 0
if (year % 400 == 0) or ((year % 4 == 0) and (year % 100 != 0)):
    leap = 1
if (leap == 1) and (month > 2):
    sum += 1
print ‘it is the %dth day.‘ % sum

  

以上是关于第四题的主要内容,如果未能解决你的问题,请参考以下文章

考试第四题

第四题

第四题数的分解

《剑指offer》第四题:替换空格

LeetCode算法第四题

CCF第四题无向图打印路径