Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sum numbers in a list but change their sign after zero is encountered

Tags:

python

list

sum

I need to sum all the numbers in the list. If 0 occurs start subtracting, until another 0, start adding.

For example:

[1, 2, 0, 3, 0, 4] -> 1 + 2 - 3 + 4 = 4
[0, 2, 1, 0, 1, 0, 2] -> -2 - 1 + 1 - 2 = -4
[1, 2] -> 1 + 2 = 3
[4, 0, 2, 3] = 4 - 2 - 3 = -1

This is what I've tried:

sss = 0

for num in numbers:
    if 0 == num:
        sss = -num
    else:
        sss += num
return sss
like image 872
Code34 Avatar asked Oct 03 '19 12:10

Code34


People also ask

How do you add numbers in a list in Python?

Python provides a method called .append() that you can use to add items to the end of a given list.


2 Answers

Change the sign when the element of the list is equal 0.

result = 0
current_sign = 1
for element in your_list:
    if element == 0:
       current_sign *= -1
    result += current_sign*element

like image 179
pawols Avatar answered Nov 15 '22 21:11

pawols


Here's a solution that cycles between two operators (addition and subtraction) whenever a value in the list is zero:

from operator import add, sub
from itertools import cycle

cycler = cycle([add, sub])
current_operator = next(cycler)

result = 0
my_list = [1, 2, 0, 3, 0, 4]

for number in my_list:
    if number == 0:
        current_op = next(cycler)
    else:
        result = current_operator(result, number)
like image 35
jfaccioni Avatar answered Nov 15 '22 23:11

jfaccioni