简体   繁体   中英

Return sum of negative and positive floating point numbers

I'm trying to create a function that takes a list of floating points and returns a list of two numbers, which is equal to the sum of all positive and all negative floating points. For example:

statement([30.95, -15.67, 45.56, -55.00, 43.78])
returns [-70.67, 120.29]

Here's what 've been able to do so far:

res= []
for i in range(len(l)-1):
    for j in range(i,len(l)):
        if l[i]>=l[i+1]:
            res = 
return res

But I'm kind of stuck. Can anyone help me understand this a little better?

I'd filter them into two lists:

positives = [n for n in numbers if n < 0]
negatives = [n for n in numbers if n > 0]

And then use sum() :

return sum(negatives), sum(positives)

Or if you want to make your instructor mad:

statement = lambda n: map(sum, zip(*map(lambda x: (x, 0)[::cmp(0, x)], n)))
def sum_negpos(numbers):
    return [sum(n for n in numbers if n < 0), # sum of negative numbers
            sum(n for n in numbers if n > 0)] # sum of positive numbers

The solution uses generator expressions (x for x in it if cond(x)) that use the same syntax as list comprehensions [x for x in it if cond(x)] but yuild one value at a time instead of creating a whole list at once.

In a single pass:

def sum_negpos(numbers):
    sums = [0, 0] # negative, positive sum
    for n in numbers:
        sums[n > 0] += n
    return sums

This solution exploits the fact that True == 1 and False == 0 in Python therefore sums[n > 0] is sums[1] if n > 0 and it is sums[0] otherwise.

Yet another solution:

def statement(l):
    return reduce(lambda (n, p), x: (x < 0) and (n + x, p) \
        or (n, p + x), l, (0, 0))

statement([30.95, -15.67, 45.56, -55.00, 43.78])
(-70.67, 120.29)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM