0

I have a list of numbers:

lst = [0, 1, 3, 4, 6, 9, 10, 11, 12, 13, 15]

and I would like to get a list of lists like so:

[[0, 1], [3, 4], [6], [9, 10, 11, 12, 13], [15]]

this means I would like to get the available continuous unique sequences from the first list.

What have I tried? I have clunky function which iterates over each element and checks if the element is equal to the previous element +1 and appends it if that was the case.

Andreas
  • 8,694
  • 3
  • 14
  • 38

2 Answers2

2

You could try something like this:

def sequences(lst):
    ret = [] # Initialise return list
    j = 0 # Index at which the last break was made
    for i, n in enumerate(lst[1:]): # Iterate through indexes and numbers
        if n != (lst[i] + 1): # Check if there is a step which is not 1
            ret.append(lst[j:i+1]) # If there is, append this portion to ret
            j = i+1 # Update j
    ret.append(lst[j:]) # Add the last portion
    return ret # Return

print(sequences([0, 1, 3, 4, 6, 9, 10, 11, 12, 13, 15]))

Output: [[0, 1], [3, 4], [6], [9, 10, 11, 12, 13], [15]]

The Thonnu
  • 3,578
  • 2
  • 8
  • 30
1

self-explanatory code:

def notSoClunkyFunc(lst):

    if len(lst)==0: return [] #returns if empty list

    ans=[] #The final result you want
    temp=[lst[0]] #the temporary list that will be added to the ans as per the question demands. 

    for i in range(1,len(lst)): #Loop that works on the same logic as suggested by you along with the question.
        if lst[i]==temp[-1]+1:
            temp.append(lst[i])
        else:
            ans.append(temp)
            temp=[]
            temp.append(lst[i])
    if len(temp): ans.append(temp)
    return ans
    
lst = [0, 1, 3, 4, 6, 9, 10, 11, 12, 13, 15]
print(notSoClunkyFunc(lst))

Output:

[[0, 1], [3, 4], [6], [9, 10, 11, 12, 13], [15]]
Amish Gupta
  • 139
  • 8