最近的一项任务是设计一个计算日期之间天数的程序。我还没有完成,我知道这可以大大改善。但是,我的问题是:当我使用date2(如下)运行此程序时,会发生错误,但这会按计划运行date1(再次,如下)。我觉得这种行为很奇怪。这些日期仅相隔一天,但有一个失败,一个没有。我已经尝试了多个日期,但无论月份、年份、日期如何,每个日期都在 994 天后失败。为什么?
澄清:我将“失败”定义为
File "first.py", line 35, in counter
return counter(date_array, x+1)
.
def date_test(date_array):
first = (date_array[0], date_array[1], date_array[2])
second = (date_array[3], date_array[4], date_array[5])
if first > second:
return False
elif first != second:
return True
elif first == second:
return False
else:
return "Error: This shouldn't happen."
def counter(date_array, x = 0):
months = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
while(date_test(date_array)):
if(date_array[2] == 31 and date_array[1] == 12):
date_array[0] += 1; date_array[1], date_array[2] = 1, 1
return counter(date_array, x+1)
else:
if date_array[2] < months[date_array[1]-1]:
date_array[2] += 1
return counter(date_array, x+1)
else:
date_array[1] += 1; date_array[2] = 1;
return counter(date_array, x+1);
return x
def tuple_test(date):
date_array = []
for x in date:
date_array.append(x)
if not date_test(date_array):
return "The first date is before the second. Swap them."
return counter(date_array)
date1 = (1900,1,1,1902,9,22)
date2 = (1900,1,1,1902,9,23)
print tuple_test(date1)
print tuple_test(date2)