## By Websten from forums # # Given your birthday and the current date, calculate your age in days. # Compensate for leap days. # Assume that the birthday and current date are correct dates (and no time travel). # Simply put, if you were born 1 Jan 2012 and todays date is 2 Jan 2012 # you are 1 day old. # # Hint # A whole year is 365 days, 366 if a leap year. 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 dateIsAfter(year1, month1, day1, year2, month2, day2): """Returns True if year1-month1-day1 is after year2-month2-day2. Otherwise, returns False.""" if year1 > year2: return True if year1 == year2: if month1 > month2: return True if month1 == month2: return day1 > day2 return False def AssertionError(year1, month1, day1, year2, month2, day2): if day1>31 or day2>31 or month1>12 or month2>12: return False if year2<year1: return False if year2==year1: if month2<month1: return 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.""" # program defensively! Add an assertion if the input is not valid! days = 0 while dateIsAfter(year2, month2, day2, year1, month1, day1): days += 1 (year1, month1, day1) = nextDay(year1, month1, day1) 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), ((2013,1,1,1999,12,31), "AssertionError")] for (args, answer) in test_cases: try: result = daysBetweenDates(*args) if result != answer: print "Test with data:", args, "failed" else: print "Test case passed!" except AssertionError: if answer == "AssertionError": print "Nice job! Test case {0} correctly raises AssertionError!\n".format(args) else: print "Check your work! Test case {0} should not raise AssertionError!\n".format(args) 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