Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

python get all sequences of numbers from list of numbers

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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]]

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading