Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Longest distinct consecutive list in Python

I have a list:

a = [2, 3, 5, 6, 6, 7, 10, 11, 13, 14, 15, 16, 16, 17, 18, 20, 21]

Is it possible to make a function that shows the longest list of distinct, consecutive elements?

Please, show how to do it

In this case the answer should be:

13, 14, 15, 16, 17, 18
like image 626
Bob Avatar asked Dec 06 '25 20:12

Bob


2 Answers

Assuming your list is sorted:

>>> from itertools import groupby
>>> z = zip(a, a[1:])
>>> tmp = [list(j) for i, j in groupby(z, key=lambda x: (x[1] - x[0]) <= 1)]
>>> max(tmp, key=len)
[(13, 14), (14, 15), (15, 16), (16, 16), (16, 17), (17, 18)]
>>> list(range(_[0][0], _[-1][-1]+1))
[13, 14, 15, 16, 17, 18]

ETA: fixed last step;

like image 154
SilentGhost Avatar answered Dec 08 '25 10:12

SilentGhost


The simplest thing to do seems to be to loop through the list once, building any sequences you can find and then print the longest one.

a = [2, 3, 5, 6, 6, 7, 10, 11, 13, 14, 15, 16, 16, 17, 18, 20, 21]

seqlist = [] # List of Sequences
seq = []     # Current Sequence
last = -1

for item in a:
   # Start a new sequence if the gap from the last item is too big
   if item - last > 1:
       seqlist.append(seq)
       seq = []

   # only add item to the sequence if it's not the same as the last
   if item != last:
        seq.append(item)

   last = item

# Print longest sequence found
print max(seqlist)
like image 37
Dave Webb Avatar answered Dec 08 '25 10:12

Dave Webb



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!