我正在努力解决Udacity的CS-101课程中的这个可选问题-它要求计算两个日期之间的天数。我的代码适用于所有的测试用例,但由于某些原因,它不适用于案例1(2012年1月1日至2012年2月28日),它返回56,但实际答案是58。我不能直接谈这个问题,任何建议都将不胜感激。在def leap_year(year):
if year % 4 != 0:
return "Common Year"
elif year % 100 != 0:
return "Leap Year"
elif year % 400 != 0:
return "Common Year"
else:
return "Leap Year"
def days_in_month(month):
months = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
i = 0
days = 0
while i <= month:
days += months[i- 1]
i += 1
return days
def daysBetweenDates(year1, month1, day1, year2, month2, day2):
i = year1
leap_count = 0
while i <= year2:
if leap_year(i) == "Leap Year":
leap_count += 1
i += 1
return ((year2 - year1) * 365 + (days_in_month(month2) - days_in_month(month1)) + (day2 - day1)) + leap_count
# Test routine
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"
else:
print "Test case passed!"
test()