[英]How to count longest uninterrupted sequence of dates
我知道如何計算最長的不間斷序列看起來像
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]}')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.