-
Notifications
You must be signed in to change notification settings - Fork 5
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
finds total days between given dates
- Loading branch information
1 parent
14dc01e
commit 85984ee
Showing
1 changed file
with
62 additions
and
0 deletions.
There are no files selected for viewing
62 changes: 62 additions & 0 deletions
62
Udacity Data Structure and Algorithms Nanodegree/Introduction/daysBetweenDates.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,62 @@ | ||
# Define a daysBetweenDates procedure that would produce the | ||
# correct output if there was a correct nextDay procedure. | ||
# | ||
# Note that this will NOT produce correct outputs yet, since | ||
# our nextDay procedure assumes all months have 30 days | ||
# (hence a year is 360 days, instead of 365). | ||
# | ||
|
||
def nextDay(year, month, day): | ||
"""Simple version: assume every month has 30 days""" | ||
if day < 30: | ||
return year, month, day + 1 | ||
else: | ||
if month == 12: | ||
return year + 1, 1, 1 | ||
else: | ||
return year, month + 1, 1 | ||
|
||
|
||
def dateIsBefore(year1, month1, day1, year2, month2, day2): | ||
if year1 < year2: | ||
return True | ||
if year1 == year2: | ||
if month1 < month2: | ||
return True | ||
if month1 == month2: | ||
return day1 < day2 | ||
|
||
return False | ||
|
||
|
||
def daysBetweenDates(year1, month1, day1, year2, month2, day2): | ||
"""Returns the number of days between year1/month1/day1 | ||
and year2/month2/day2. Assumes inputs are valid dates | ||
in Gregorian calendar, and the first date is not after | ||
the second.""" | ||
|
||
# YOUR CODE HERE! | ||
days = 0 | ||
while dateIsBefore(year1, month1, day1, year2, month2, day2): | ||
year1, month1, day1 = nextDay(year1, month1, day1) | ||
days += 1 | ||
|
||
return days | ||
|
||
|
||
def test(): | ||
test_cases = [((2012, 9, 30, 2012, 10, 30), 30), | ||
((2012, 1, 1, 2013, 1, 1), 360), | ||
((2012, 9, 1, 2012, 9, 4), 3)] | ||
|
||
for (args, answer) in test_cases: | ||
result = daysBetweenDates(*args) | ||
if result != answer: | ||
print("Test with data:", args, "failed") | ||
else: | ||
print("Test case passed!") | ||
|
||
|
||
|
||
test() | ||
|