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
Python provides a method called .append() that you can use to add items to the end of a given list.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With