0

I am learning Python and took on a few CodeWars exercises to get more familiar with its methods.

I have this function that creates the sum of all positive integers, and although I know there might be a "one liner" way to do this, this is approach I am taking as a beginner:

def positive_sum(arr):
    for x in arr:
        if x <= 0:
            arr.remove(x)
    
    if len(arr) == 0:
        return 0
    
    print(arr)
    
    return sum(arr)

For some reason this method is not removing -2, and -4 from the array. Why is that?

@test.it("returns 0 when all elements are negative")
    def negative_case():
        test.assert_equals(positive_sum([-1,-2,-3,-4,-5]),0)

Python error message

martineau
  • 119,623
  • 25
  • 170
  • 301

1 Answers1

1

Here is a way you can do it.

x = [-6, -4, 3, 5]
x = sum([i for i in x if i>0])
print(x)
eatmeimadanish
  • 3,809
  • 1
  • 14
  • 20