python function to find sum of positive numbers in an array

13,158

Solution 1

Use super functions and list comprehension instead:

>>> a = [1, 2, 3, -4, 5, -3, 7, 8, 9, 6, 4, -7]
>>> sum(x for x in a if x > 0)
45

[x for x in a if x > 0] will create an array made of the positive values in a.

sum(...) will return the sum of the elements in that array.

Solution 2

There are better approaches with sums and comprehensions, but I'll assume you're writing a function as an exercise in algorithms.

You don't need the while loop. Use an if to check if it is positive, and add it to the sum. Otherwise, don't do anything. The for loop will automatically iterate over the values for you.

def maximum_sum(A):
    x = 0
    for i in A:
        if i > 0:
            x += i
    return x

A few words of advice: name things expressively. Here's some names I might use:

def maximum_sum(arr):
    max_sum = 0
    for num in arr:
        if num > 0:
            max_sum += num
    return max_sum
Share:
13,158
SHirsch
Author by

SHirsch

Updated on June 22, 2022

Comments

  • SHirsch
    SHirsch almost 2 years

    i need to write a function that takes an array of numbers and finds the maximum sum of all the numbers. In other words, I need to find the sum of just the positive numbers. I wrote this, I'm getting "list is out of range"

    thoughts?

        def maximum_sub(A):
            x = 0
            i = 0
            for i in A:
                while A[i] > 0:
                x+=A[i]
                i+=1
            return x