Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find/extract a sequence of integers within a list in python

Tags:

python

I want to find a sequence of n consecutive integers within a sorted list and return that sequence. This is the best I can figure out (for n = 4), and it doesn't allow the user to specify an n.

my_list = [2,3,4,5,7,9]
for i in range(len(my_list)):
    if my_list[i+1] == my_list[i]+1 and my_list[i+2] == my_list[i]+2 and my_list[i+3] == my_list[i]+3:
        my_sequence = list(range(my_list[i],my_list[i]+4))

my_sequence = [2,3,4,5]

I just realized this code doesn't work and returns an "index out of range" error, so I'll have to mess with the range of the for loop.

like image 603
rspears69 Avatar asked Oct 09 '15 01:10

rspears69


People also ask

How do I extract the last 3 items from a list in Python?

Method #2 : Using islice() + reversed() The islice function can be used to get the sliced list and reversed function is used to get the elements from rear end.


2 Answers

Here's a straight-forward solution. It's not as efficient as it might be, but it will be fine unless you have very long lists:

myarray = [2,5,1,7,3,8,1,2,3,4,5,7,4,9,1,2,3,5]
for idx, a in enumerate(myarray):
    if myarray[idx:idx+4] == [a,a+1,a+2,a+3]:
        print([a, a+1,a+2,a+3])
        break
like image 112
saulspatz Avatar answered Oct 29 '22 16:10

saulspatz


Create a nested master result list, then go through my_sorted_list and add each item to either the last list in the master (if discontinuous) or to a new list in the master (if continuous):

>>> my_sorted_list = [0,2,5,7,8,9]
>>> my_sequences = []
>>> for idx,item in enumerate(my_sorted_list):
...     if not idx or item-1 != my_sequences[-1][-1]:
...         my_sequences.append([item])
...     else:
...         my_sequences[-1].append(item)
...
>>> max(my_sequences, key=len)
[7, 8, 9]
like image 40
TigerhawkT3 Avatar answered Oct 29 '22 16:10

TigerhawkT3