简体   繁体   中英

Computing Positive/Negative Numbers Averages in Python

I've written most of my code out, however, I'm having problems with computing the average for the positive numbers as well as the negative numbers in a given list. The function works giving me the list and shows me the numallavg, but doesn't work for the positive and negative functions. This is my whole code:

def numbersList():
    values = []
    while -9999 not in values:
        x = int(input('Enter any amount of numbers (-9999 to end): '))
        values.append(x)
    values.remove(-9999)
    print('This list of all numbers entered is: ')
    print(values)
    return values

def allNumAvg(values):
    average = 0
    sum = 0
    for n in values:
        sum = sum + n
    average = (sum / len(values))
    return average

print(allNumAvg(numbersList()))

def posNumAvg(values):
    x = []
    average = 0
    sum = 0
    if int in values > 0:
        x.append(int)
    print(x)

def nonPosAvg(values):
    y = []
    average = 0
    sum = 0
    if int in values < 0:
       y.append(int)
    print(y)

Try to write those functions in a similar fashion as allNumAvg :

def posNumAvg(values):
    quantity = 0
    average = 0
    sum = 0
    for n in values:
        if n > 0:
            sum += n
            quantity += 1
    average = float(sum) / quantity
    return average

There are many things that can be improved in this code, though. For instance, average does not need to be initialized as 0 , sum is a builtin function and it's better not to use it as a name of a variable. There are also shorter versions, but try first to have a good understanding of this sort of code and then jump to other ways.

Positive:

reduce(lambda x, y: x + y, [a for a in x if a > 0]) / float(len([a for a in x if a > 0]))

Negative:

reduce(lambda x, y: x + y, [a for a in x if a < 0]) / float(len([a for a in x if a < 0]))

where a is i/p list

If you want to/can use numpy this is also really straightforward.

import numpy
def allNumAvg(values):
    return numpy.average(values)

def posNumAvg(values):
    arr_v = np.asarray(values) 
    return numpy.average(arr_v[arr_v>0]) # or do you want the zeros too?

def nonPosAvg(values):
    arr_v = np.asarray(values) 
    return numpy.average(arr_v[arr_v<0]) # or do you want the zeros too?

I actually like :

avg = lambda x: sum(x) / float(len(x))
print ("all average = %f"%avg(nums))
print ("positive average = %f"%avg([x for x in nums if x > 0])
print ("non-positive average = %f"%avg([x for x in nums if x <= 0])

But, that's probably "trickier" than the teacher is looking for on this assignment

You want to do the same calculation on three different (although related) sets of data. That sounds like time to define a function and call it multiple times passing in different parameters.

the calculation itself is simply the sum of a list of numbers divided by the length of the list. Python has both of those functions built-in (sum([list]) and len(iterator)) :

sum(x)/float(len(x))

Let's make sure we do a floating point division to make sure it works for different versions of python and different lists of data.

def avg(x):
    return (sum(x) / float(len(x)))

I dislike one line functions, so lets inline that with lambda and assign it to the name:

avg = lambda x: sum(x) / float(len(x))

Then just use list comprehensions to filter the list of data you are passing for the different calls:

[x for x in nums if x > 0]

I want a list of values in the iterator nums where the value is greater than 0.

Insert that into the call to avg and you have:

    avg([x for x in nums if x > 0])

we want to print our results. lets give it a label while we are at it. There's no need to store the value in a temporary spot, let's just pass the result of the call to print:

    print ("positive average = %f"%avg([x for x in nums if x > 0])

Edit:

I just noticed that you did not store your list of values that you got from your first function. You want to store your list of values, then start processing it in different ways:

print(allNumAvg(numbersList()))

needs to be:

nums = numbersList()
print(allNumAvg(nums))

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