return a list of numbers that are in sequence

Asked

Viewed 61 times

1

I’m trying to make some list go through and make another one come back with the numbers that are in sequence.

My list is returning empty.

Ex: lista=[1,2,3,5,9,10] returns nova_lista=[1,2,3,9,10]

sequencial= []
def seq (lista):
     for i in range(0,len(lista)-1):
         if lista[i] == lista[i+1]:
             sequencial.append[i]
     return sequencial

1 answer

3


The problem is that if lista[i] == lista[i+1] compares whether the element is equal to the next. And since the list has no repeated elements, the result will always be empty (as it will never enter this if).

A solution would be to scroll through the list from the second element and check if it is equal to "previous + 1":

lista = [1, 2, 3, 5, 9, 10]
result = []
in_seq = False
for i in range(1, len(lista)):
    if lista[i] == lista[i - 1] + 1:
        if not in_seq:
            result.append(lista[i - 1])
            in_seq = True
        result.append(lista[i])
    else:
        in_seq = False

print(result)

I also used the variable in_seq to know if I’m in the middle of a sequence, because if I’m not, I also have to include the previous element in the result.

The result is:

[1, 2, 3, 9, 10]
  • 1

    Perfect, I could understand everything that was explained.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.