-2

This is my original list:

list1 = [1,2,5,-2,-3,5,6,-3,0,-2,1,0,2]

I need to create a list of sum-up positive and negative as below:

list2 = [8,-5,11,-5,3]
wjandrea
  • 28,235
  • 9
  • 60
  • 81

3 Answers3

1

Here is the solution with comment lines.

list1 = [1,2,5,-2,-3,5,6,-3,0,-2,1,0,2]

list2 = []

temp = 0
lastPositive = False

for i in list1: #Iterate through the list
    if (i == 0): #If i is zero, continue
        continue
    if ((i > 0) == (1 if lastPositive else 0)): #if last element is positive and now is positive, add i to temp
        temp += i
    else: #if not, the positivity changes and add temp to list2
        lastPositive = not lastPositive #Change the last positivity
        list2.append(temp) if temp != 0 else print()
        temp = i #Set temp to i for the rest of the list

list2.append(temp)
print(list2) #Then print the list
wjandrea
  • 28,235
  • 9
  • 60
  • 81
1

You can filter out zero elements, then use itertools.groupby() to group the same-signed items together, and then sum those.

from itertools import groupby

def group_by_sign(values):
    nonzero = filter(None, values)  # filters out falsey values
    is_positive = lambda x: x > 0
    return [sum(group) for key, group in groupby(nonzero, is_positive)]

Example usage:

>>> values = [1, 2, 5, -2, -3, 5, 6, -3, 0, -2, 1, 0, 2]
>>> print(group_by_sign(values))
[8, -5, 11, -5, 3]
Dillon Davis
  • 6,679
  • 2
  • 15
  • 37
  • Beside the point, but [avoid named lambdas](/q/38381556/4518341). I would just put it inline here since it's so simple and only used once. – wjandrea Jan 29 '22 at 23:55
  • 1
    @wjandrea you are correct, and the Python PEP agrees with you, but I respectfully disagree with it. I want the benefit of self-documentation from naming it, without drawing unnecessary attention to that line by adding an indentation level. Yes, lambda exist to be be anonymous functions, but they have an implicit association with being "throw away" functions, and I wish to preserve that association. – Dillon Davis Jan 30 '22 at 01:14
1

Keep summing, append/reset at sign changes.

list2 = []
s = 0
for x in list1:
    if s * x < 0:
        list2.append(s)
        s = 0
    s += x
if s:
    list2.append(s)
Kelly Bundy
  • 23,480
  • 7
  • 29
  • 65