# Credit goes to Websten from forums # # Use Dave's suggestions to finish your daysBetweenDates # procedure. It will need to take into account leap years # in addition to the correct number of days in each month. def is_leap_year(year): if year%4 != 0: return False elif year%100 != 0: return True elif year%400 != 0: return False else: return True def days_in_month(month, year): month_lengths = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 31, 31] return 29 if month == 2 and is_leap_year(year) else month_lengths[month] def nextDay(year, month, day): day = day + 1 if day < days_in_month(month, year) else 1 if day == 1: if month == 12: month = 1 else: month = month + 1 year = year + 1 if month == 1 and day == 1 else year return (year, month, day) 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 tempYear = year1 tempMonth = month1 tempDay = day1 while (tempYear, tempMonth, tempDay) != (year2, month2, day2): (tempYear, tempMonth, tempDay) = nextDay(tempYear, tempMonth, tempDay) days = days + 1 return days def test(): test_cases = [ ((2012,2,1,2012,2,1), 0), ((2012,2,1,2012,2,2), 1), ((2012,2,1,2012,2,28), 27), ((2012,2,1,2012,2,29), 28), ((2012,2,1,2012,3,1), 29), ((2011,2,1,2011,2,1), 0), ((2011,2,1,2011,2,2), 1), ((2011,2,1,2011,2,28), 27), ((2011,2,1,2011,3,1), 28), ] for (args, answer) in test_cases: result = daysBetweenDates(*args) if result != answer: print "Test with data:", args, "failed" else: print "Test case passed!" test()
Run
Reset
Share
Import
Link
Embed
Language▼
English
中文
Python Fiddle
Python Cloud IDE
Follow @python_fiddle
Browser Version Not Supported
Due to Python Fiddle's reliance on advanced JavaScript techniques, older browsers might have problems running it correctly. Please download the latest version of your favourite browser.
Chrome 10+
Firefox 4+
Safari 5+
IE 10+
Let me try anyway!
url:
Go
Python Snippet
Stackoverflow Question