我知道如何计算看起来像的最长不间断序列
list = [0, 0, 1, 0, 1, 1, 1, 0, 1, 1, 0]
现在我正试图用这样的日期列表来解决这个问题
date1 = datetime.date(2021, 5, 11)
date2 = datetime.date(2021, 5, 12)
date3 = datetime.date(2021, 5, 18)
date4 = datetime.date(2021, 5, 19)
date5 = datetime.date(2021, 5, 20)
date6 = datetime.date(2021, 5, 25)
date7 = datetime.date(2021, 5, 26)
date_list = [date1, date2, date3, date4, date5, date6, date7]
我正在寻找最长的不间断的一天。我试图将天数序列转换为类似于第一个列表的内容,1表示1天的差异(不间断(,0表示一天以上的差异(间断(,但到目前为止,我根本无法想出解决方案。
假设它已排序
longest_start_index = 0
longest_end_index = 0
current_start_index = 0
current_end_index = 0
curr_date = date_list[0]
while (current_end_index < len(date_list)):
next_date = date_list[current_end_index]
if (next_date-curr_date).days > 1:
# next day is more than 1 day away so reset start index
current_start_index = current_end_index
else:
if (current_end_index - current_start_index) > (longest_end_index - longest_start_index):
longest_start_index = current_start_index
longest_end_index = current_end_index
current_end_index = current_end_index + 1
curr_date = next_date
print(f'Longest continuous sequence is from {date_list[longest_start_index]} to {date_list[longest_end_index]}')