Create list with the sum of consecutive equal numbers

Asked

Viewed 347 times

-2

That’s my structure, but the if, elif and even the else (although not in the code), they are not working. The code is printing several lines as if they were if'separate s and the function has to add consecutive equal numbers.

Example: If inserted [1,2,2,2,3,4,4], the program has to return [1,6,3,8].

lista  = []
lista1 = []

while len(lista) + 1 < 8:
 lista.append(int(input("Digite o valor: ")))

print(lista)

for i in range(1, len(lista)):

    if lista[i - 1] == lista[i] and lista[i] == lista[i + 1]:

        lista1.append(lista[i - 1] + lista[i] + lista[i + 1])

    elif lista[i - 1] == lista[i]:

        lista1.append(lista[i - 1] + lista[i])

    elif lista[i - 1] != lista[i]: 

        lista1.append(lista[i])
        print(lista[0], lista1)

print(lista1)

3 answers

0


You can use the function groupby() of the standard library itertools, look at you:

from itertools import groupby

entrada = [1,2,2,2,3,4,4]

saida = [sum(i) for _, i in groupby(entrada)]

print(saida)

Exit:

[1, 6, 3, 8]

See working on Repl.it

0

lista = [1,2,2,2,3,4,4]

def func(lista):
    resultado = []
    soma = lista[0]
    for i in range(1, len(lista)):
        if lista[i] == lista[i-1]:
            soma += lista[i]
            if i == len(lista)-1:
                resultado += [soma]
        else:
            resultado += [soma]
            soma = lista[i]
    return resultado

func(lista)

0

One mistake is in the first if. How do you do the for i in range(1, len(lista)), what happens when i arrives in len(lista) - 1?

For example, for the list [ 1, 2, 2, 2, 3, 4, 4 ], which has 7 elements, the valid indices are from 0 to 6. When i comes in 6, you do in the first if:

if lista[i - 1] == lista[i] and lista[i] == lista[i + 1]:

When you do lista[i + 1], is trying to access index 7, which does not exist in the list, and occurs a IndexError. And the code is printing several lines because you put a print at last elif, so every time you fall there you print something.

But the main problem is the algorithm itself. The first if checks that the element is equal to the previous and the next, and already inserts the sum of the 3 in the result list. But what if it has 4 (or more) consecutive numbers equal? You should only enter in the results list when the number changes (in addition to updating the sum while the number does not change). An alternative is to do so:

def somar_consecutivos(lista):
    sum = ant = lista[0]
    res = []
    for i in range(1, len(lista)):
        n = lista[i]
        if n == ant:
            sum += n
        else:
            res.append(sum)
            sum = n
        ant = n
    res.append(sum)
    return res

print(somar_consecutivos([1, 4, 4, 4, 0, 4, 3, 3, 1])) # [1, 12, 0, 4, 6, 1]
print(somar_consecutivos([5, 5, 5, 5, 5, 5, 0, 2, 3, 3])) # [30, 0, 2, 6]
print(somar_consecutivos([1, 2, 2, 2, 3, 4, 4])) # [1, 6, 3, 8]
print(somar_consecutivos([1, 2, 3, 4, 5])) # [1, 2, 3, 4, 5]

I start with the first element of the list, and then, for the other elements, I always check if it is the same as the previous one. If it is, I update the sum, and if it is not (ie the number has changed), then yes I add the sum accumulated so far in the list of results.

Browser other questions tagged

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