Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find the longest consecutive chain of numbers in an array

Tags:

python

arrays

For example we have [0, 1, 3, 5, 7, 8, 9, 10, 12, 13] .

The result must be 7, 8, 9, 10 because they are adjacent to each other, index wise and are consecutive integers, and also this chain is longer than 0, 1.

English is not my first language, excuse me if the writing is a bit obscure.

like image 650
Divisor_13 Avatar asked Oct 22 '25 14:10

Divisor_13


1 Answers

Group the items into subsequences using itertools.groupby based on constant differences from an increasing count (provided by an itertools.count object), and then take the longest subsequence using the built-in max on key parameter len:

from itertools import groupby, count

lst = [0, 1, 3, 5, 7, 8, 9, 10, 12, 13]
c = count()
val = max((list(g) for _, g in groupby(lst, lambda x: x-next(c))), key=len)
print(val)
# [7, 8, 9, 10]

You may include the group key in the result (suppressed as _) to further understand how this works.

like image 116
Moses Koledoye Avatar answered Oct 24 '25 04:10

Moses Koledoye