-2

Edit 1: Solved! The solution was using i for i in arr if i > 0, which was given to me by @sushanth.

Final product of the code:

def positive_sum(arr):
    return sum(i for i in arr if i > 0)

I am trying to complete some Codewars challenges, and I came across one that is giving me issues. I am given a list of positive and negative numbers, and I am supposed to find the sum of all of the positive numbers.

Here is what I already have:

def positive_sum(arr):
    for n in arr:
        if n < 0:
            arr.remove(n)
    return sum(arr)

Here are the lists I am supposed to be working on:

[1,2,3,4,5]
[1,-2,3,4,5]
[-1,2,3,4,-5]
[]      
[-1,-2,-3,-4,-5]

However, whenever I run the tests, all of the tests pass except for the last one, with all of the negative numbers. For some reason, the result of it is -6, even though all negative numbers should have been removed.

Why is this? What should I do to make sure all of the tests pass?

1 Answers1

2

try sum() with generator and if condition:

result = sum(x for x in [1, 2, 3, 4, 5] if x > 0)
print(result)
Vova
  • 3,117
  • 2
  • 15
  • 23
  • 2
    No need to use a `list` comprehension, `sum()` can take a generator as an argument. Creating a `list` first wastes memory and computation time. – ddejohn Mar 09 '21 at 17:51
  • Although, play around with it. Generator expressions also tend to be slower, so for small lists, a comprehension may be the better option if the extra memory usage is acceptable. – Carcigenicate Mar 09 '21 at 17:54
  • entirely agreed, changed to generator, good catch, thanks! – Vova Mar 09 '21 at 17:56