-1

I have a list and I have to find consecutive sequences in that list.

For example if my list is [1,2,3,5,7,8,9] then code should return [1,2,3] and [7,8,9]

And if the list is [3,5,6,7,8,10] it should return [5,6,7,8]

Please suggest me something how I can code it to find the consecutive sub-sequences?

razdi
  • 1,288
  • 14
  • 18
Kanika Singhal
  • 203
  • 1
  • 2
  • 8

1 Answers1

0
my_cons = [3,5,6,7,8,10]

end = len(my_cons)
curr = 0
longest_seq = 0
longests = []

while curr < end:
    tmp_curr = curr;
    while tmp_curr < end-1:
        if my_cons[tmp_curr] +1 == my_cons[tmp_curr+1]:
            tmp_curr += 1
        else:
            break
    if tmp_curr - curr > longest_seq:
        longest_seq = tmp_curr - curr
        longests = [my_cons[curr:tmp_curr+1]]
    elif tmp_curr - curr == longest_seq:
        longests.append(my_cons[curr:tmp_curr+1])
    curr = tmp_curr + 1

print (longests)
Tom Ron
  • 5,322
  • 2
  • 16
  • 32