简体   繁体   中英

Find/extract a sequence of integers within a list in 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.

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

A short and concise way is to fill an array with numbers every time you find the next integer is the current integer plus 1 (until you already have N consecutive numbers in array), and for anything else, we can empty 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 is run, newarr will be:

[1, 2, 3, 4]

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]
#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 []
mylist = [2,3,4,5,7,9]
for j in range(len(mylist)):
      m=mylist[j]
      idx=j
      c=j
      for i in range(j,len(mylist)):
               if mylist[i]<m:
                          m=mylist[i]
                          idx=c
               c+=1
      tmp=mylist[j]
      mylist[j]=m
      mylist[idx]=tmp
print(mylist)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM