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.