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

Viewed 427

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

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)

Try this:

d = [1, 2, 0, 3, 0, 4]

sum = 0
sign = False
for i in d:
    if i == 0:
        if sign == False:
            sign = True
        else:
            sign = False
    else:
        if sign == False:
            sum += i
        else:
            sum -= i
print(sum)

Another variation with operator module and bitwise negation ~:

import operator

def accum_on_zero(lst):
    res = 0
    ops, pos = (operator.add, operator.sub), 0
    for i in lst:
        if i == 0:
            pos = ~pos
        res = ops[pos](res, i)
    return res


print(accum_on_zero([1, 2, 0, 3, 0, 4]))     # 4
print(accum_on_zero([0, 2, 1, 0, 1, 0, 2]))  # -4 
lst = [1, 2, 0, 3, 0, 4]
print(sum([v * (-1) ** lst[0:i].count(0) for i, v in enumerate(lst)]))
Related