1
+
2
+ # Use Dave's suggestions to finish your daysBetweenDates
3
+ # procedure. It will need to take into account leap years
4
+ # in addition to the correct number of days in each month.
5
+
6
+
7
+ def leapYear (year ):
8
+ if year % 400 == 0 :
9
+ return True
10
+ if year % 100 == 0 :
11
+ return False
12
+ if year % 4 == 0 :
13
+ return True
14
+ return False
15
+
16
+
17
+ def daysInMonth (year , month ):
18
+ if month == 1 or month == 3 or month == 5 or month == 7 or month == 8 or month == 10 or month == 12 :
19
+ return 31
20
+ else :
21
+ if month == 2 :
22
+ if leapYear (year ):
23
+ return 29
24
+ else :
25
+ return 28
26
+ else :
27
+ return 30
28
+
29
+
30
+ def nextDay (year , month , day ):
31
+ """Simple version: assume every month has 30 days"""
32
+ if day < daysInMonth (year , month ):
33
+ return year , month , day + 1
34
+ else :
35
+ if month == 12 :
36
+ return year + 1 , 1 , 1
37
+ else :
38
+ return year , month + 1 , 1
39
+
40
+
41
+ def dateIsBefore (year1 , month1 , day1 , year2 , month2 , day2 ):
42
+ """Returns True if year1-month1-day1 is before year2-month2-day2. Otherwise, returns False."""
43
+ if year1 < year2 :
44
+ return True
45
+ if year1 == year2 :
46
+ if month1 < month2 :
47
+ return True
48
+ if month1 == month2 :
49
+ return day1 < day2
50
+ return False
51
+
52
+
53
+ def daysBetweenDates (year1 , month1 , day1 , year2 , month2 , day2 ):
54
+ """Returns the number of days between year1/month1/day1
55
+ and year2/month2/day2. Assumes inputs are valid dates
56
+ in Gregorian calendar."""
57
+ # program defensively! Add an assertion if the input is not valid!
58
+
59
+ assert not dateIsBefore (year2 , month2 , day2 , year1 , month1 , day1 )
60
+
61
+ days = 0
62
+
63
+ while dateIsBefore (year1 , month1 , day1 , year2 , month2 , day2 ):
64
+ year1 , month1 , day1 = nextDay (year1 , month1 , day1 )
65
+ days += 1
66
+ return days
67
+
68
+
69
+ def test ():
70
+ test_cases = [((2012 , 1 , 1 , 2012 , 2 , 28 ), 58 ),
71
+ ((2012 , 1 , 1 , 2012 , 3 , 1 ), 60 ),
72
+ ((2011 , 6 , 30 , 2012 , 6 , 30 ), 366 ),
73
+ ((2011 , 1 , 1 , 2012 , 8 , 8 ), 585 ),
74
+ ((1900 , 1 , 1 , 1999 , 12 , 31 ), 36523 )]
75
+
76
+ for (args , answer ) in test_cases :
77
+ result = daysBetweenDates (* args )
78
+ if result != answer :
79
+ print ("Test with data:" , args , "failed" )
80
+ else :
81
+ print ("Test case passed!" )
82
+
83
+
84
+ test ()
0 commit comments