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

I want to find a sequence of n consecutive integers in a sorted list and return this sequence. This is the best I can figure out (for n = 4), and it does not allow the user to specify 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 that this code is not working and it returns an "index out the range" error, so I have to mess up the range of the for loop.

+6
source share
4 answers

A short and concise way is to populate the array with numbers every time you find the next integer - the current integer plus 1 (until you already have N consecutive numbers in the array), and for something else, we can clear the array

 arr = [4,3,1,2,3,4,5,7,5,3,2,4] N = 4 newarr = [] for i in range(len(arr)-1): if(arr[i]+1 == arr[i+1]): newarr += [arr[i]] if(len(newarr) == N): break else: newarr = [] 

When the code starts, newarr will be:

 [1, 2, 3, 4] 
+2
source

Here is a direct solution. This is not as efficient as it could be, but it will be good if your lists are too long:

 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 
+3
source

Create a nested list of result results, then go through my_sorted_list and add each item to the last list in master (if it breaks) or to a new list in the main (if it runs continuously):

 >>> 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] 
+1
source
 #size = length of sequence #span = the span of neighbour integers #the time complexity is O(n) def extractSeq(lst,size,span=1): lst_size = len(lst) if lst_size < size: return [] for i in range(lst_size - size + 1): for j in range(size - 1): if lst[i + j] + span == lst[i + j + 1]: continue else: i += j break else: return lst[i:i+size] return [] 
0
source

All Articles