Python DaysBetweenDate
Solution 1:
Your daysBetweenDates()
algorithm does indeed have an infinite loop.
while dateIsBefore(year1, month1, day1, year2, month2, day2):
days += 1
You never modify any of the year/month/day values here in the loop, so if the condition is true once, it will be true forever.
The solution, in concept, would be to decrease day2
by one every time, so when the two dates become equal, days
will be the day difference between them. However, since you said you made the assumption that each month has 30 days, you're overcomplicating things for yourself. You can find the day difference between two dates by converting the (year, month, day) tuple to a day value. For example,
def days_between_dates(y1, m1, d1, y2, m2, d2):
date1 = y1*360 + (m1-1)*30 + d1
date2 = y2*360 + (m2-1)*30 + d2
# assuming you want to return 0 if date2 is before date1
return date2 - date1 if date2 >= date1 else 0
Solution 2:
This solution counts daysInMonth correctly, doesn't involve any kind of infinite loop, counts correct dates in a leap year and provides an exact answer to inputs. The solution is written in Python.
def daysInMonth(m,y):
if m == 1 or m == 3 or m == 5 or m == 7 or m == 8 or m ==10 or m == 12:
return 31
else :
if m == 2:
if isLeapYear(y):
return 29
return 28
return 30
def nextDay(y,m,d):
if d < daysInMonth(m,y):
return y, m, d+1
else:
if m == 12:
return y + 1, 1, 1
else:
return y, m + 1, 1
def isLeapYear(y):
if y % 400 == 0:
return True
elif y % 4 == 0:
return True
else:
if y % 100 == 0:
return False
return False
def dateIsBefore(y1, m1, d1, y2, m2, d2):
days = 0
if y1 < y2 :
return True
if y1 == y2:
if m1 < m2:
return True
if m1 == m2:
return d1<d2
return False
def daysbetweendates(y1, m1, d1, y2, m2, d2):
days = 0
while dateIsBefore(y1, m1, d1, y2, m2, d2):
y1, m1, d1 = nextDay(y1, m1, d1)
days = days + 1
return days
def test():
test_cases = [((2012,1,1,2012,2,28), 58),
((2012,1,1,2012,3,1), 60),
((2011,6,30,2012,6,30), 366),
((2011,1,1,2012,8,8), 585 ),
((1900,1,1,1999,12,31), 36523)]
for (args, answer) in test_cases:
result = daysbetweendates(*args)
if result != answer:
print "Test with data:", args, "failed"
print result
else:
print "Test case passed!"
test()
Solution 3:
The function dateIsBefore
is incomplete.
def dateIsBefore(year1, month1, day1, year2, month2, day2):
if year1 < year2:
return True
if year1 == year2 and month1 < month2:
return True
if year1 == year2 and month1 == month2 and day1 < day2:
return True
return False
(It could be simplified, but I left it like this for clarity. Also, of course, you could use datetime.date
--someone else already made that comment; see also other answer that tells you to increment year1,month1, and day1)
Solution 4:
dateIsBefore will always return True.
Post a Comment for "Python DaysBetweenDate"