Вариант #1 (для возрастающих субпоследовательностей):
from itertools import count
def subsequences(sequence):
start = 0
expected = count(sequence[start])
last_index = len(sequence) - 1
for end, val in enumerate(sequence):
flag_val = val == next(expected)
flag_end = end == last_index
if flag_val:
if flag_end:
yield sequence[start:]
continue
yield sequence[start:end]
if flag_end:
yield sequence[end:]
continue
expected = count(sequence[end+1])
start = end
def solve(sequence):
return max(subsequences(sequence), key=len)
if __name__ == '__main__':
sequence = [0, 2, 3, 6, 7, 8, 9, 10, 13, 14, 15, 16, 20]
print(solve(sequence)) # => [6, 7, 8, 9, 10]
Вариант #2 (универсальный, т.к. считает модуль разности):
from operator import sub
from itertools import groupby
def solve(sequence, step=1):
pairs = zip(sequence[:-1], sequence[1:])
criteria = lambda pair: abs(sub(*pair)) == step
grouped = groupby(pairs, key=criteria)
subsequences = (tuple(group) for flag, group in grouped if flag)
result, extra = zip(*max(subsequences, key=len))
return result + extra[-1:]
if __name__ == '__main__':
sequence = [0, 2, 3, 6, 7, 6, 7, 8, 9, 10, 13, 14, 15, 16, 20]
print(solve(sequence)) # => (6, 7, 6, 7, 8, 9, 10)
Первый способ в 1.5 раза быстрее второго.