Python - 按天算年龄

问题:输入出生日期和当前的日期,输出活了多少天

举例:你是昨天出生的,那么输出就为1

分三种情况讨论:

1、年份和月份都相同

2、年份相同月份不同,先计算出生当天是当年的第几天,后计算当前为当年的第几天,相减

3、年份不同,还是先计算出生当天为当年的第几天,后计算当前为当年的第几天,做闰年判断,逐一相加

闰年为一下两种情况

1、能被400整除

2、能被4整除但不能被100整除

 

、、、、、、、、、、、、、、、

 

本题来自Udacity的计算机科学导论课程,用来做Python入门

 1 # By Websten from forums
 2 #
 3 # Given your birthday and the current date, calculate your age in days.
 4 # Account for leap days.
 5 #
 6 # Assume that the birthday and current date are correct dates (and no
 7 # time travel).
 8 #
 9 
10 
11 def is_leap(year):
12     result = False
13     if year % 400 == 0:
14         result = True
15     if year % 4 == 0 and year % 100 != 0:
16         result = True
17     return result
18 
19 
20 def days_between_dates(year1, month1, day1, year2, month2, day2):
21     days_of_months = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
22     if year1 == year2 and month1 == month2:
23         days = day2 - day1
24     if year1 == year2:
25         days1 = 0
26         i = 0
27         while i < month1 - 1:
28             days1 = days1 + days_of_months[i]
29             i = i + 1
30         days1 = days1 + day1
31         if is_leap(year1) and month1 > 2:
32             days1 = days1 + 1
33         days2 = 0
34         i = 0
35         while i < month2 - 1:
36             days2 = days2 + days_of_months[i]
37             i = i + 1
38         days2 = days2 + day2
39         if is_leap(year2) and month2 > 2:
40             days2 = days2 + 1
41         days = days2 - days1
42     else:
43         days1 = 0
44         i = 0
45         while i < month1 - 1:
46             days1 = days1 + days_of_months[i]
47             i = i + 1
48         days1 = days1 + day1
49         if is_leap(year1) and month1 > 2:
50             days1 = days1 + 1
51         days2 = 0
52         i = 0
53         while i < month2 - 1:
54             days2 = days2 + days_of_months[i]
55             i = i + 1
56         days2 = days2 + day2
57         if is_leap(year2) and month2 > 2:
58             days2 = days2 + 1
59         days = 365 - days1 + days2
60         if is_leap(year1):
61             days = days + 1
62         year1 = year1 + 1
63         while year1 < year2:
64             days = days + 365
65             year1 = year1 + 1
66             if is_leap(year1):
67                 days = days + 1
68     return days
69 
70 
71 # Test routine
72 
73 def test():
74     test_cases = [((2012, 1, 1, 2012, 2, 28), 58),
75                   ((2012, 1, 1, 2012, 3, 1), 60),
76                   ((2011, 6, 30, 2012, 6, 30), 366),
77                   ((2011, 1, 1, 2012, 8, 8), 585),
78                   ((1900, 1, 1, 1999, 12, 31), 36523)]
79     for (args, answer) in test_cases:
80         result = days_between_dates(*args)
81         if result != answer:
82             print("Test with data:", args, "failed")
83         else:
84             print("Test case passed!")
85 
86 
87 test()

 

posted @ 2018-03-29 01:57  自由的青  阅读(3052)  评论(1编辑  收藏  举报