У меня есть следующий список чисел:
numbers = numbers = [ 1, 3, 11, 12, 14, 15, 16, 3, 4, 6]
Я хотел бы получить начальный и конечный индексы самого длинного последовательного диапазона чисел.Под последовательным диапазоном я подразумеваю целочисленный диапазон числа без пропуска, то есть 1,2,3,4,5 ...
Вот как я это сделал:
def get_longest_consecutive_numbers(numbers):
# 1. Split the numbers list into sublists of consecutive numbers
split_list = []
j = 0
for i in range(1,len(numbers)-1):
if numbers[i]+1 is not numbers[i+1]:
split_list.append(numbers[j:i])
j = i
# 2. Find index of longest sublist (of consecutive numbers)
longest_sublist_index = max((len(l), i) for i, l in enumerate(split_list))[1]
# 3. Concatenate all sublists up to this index back together
rest = split_list[:longest_sublist_index]
concat_list = [j for i in rest for j in i]
# 4.
# Start Index: Length of concatenated list
# End Index: Start Index + Length of longest sublist in split_list
start_index = len(concat_list)
end_index = start_index + len(split_list[longest_sublist_index])
return start_index, end_index
Если я применяю свою функцию к списку чисел:
get_longest_consecutive_numbers(numbers)
, я получаю:
(3, 6)
, что правильно ... но ...
Мне было интересно, есть ли более прямой (лучший) способ сделать это?