简体   繁体   中英

how to modify average function in python?

How do I change the code below so that when a minus number is found it skips it (eg -1 ) and returns the averages of only positive numbers? (eg 0 and above)

def Avg(B):
    sum = 0
    for b in B:
        sum = sum + b
    return sum/len(B)

First off, don't use sum as a name, it will mask the built in sum function.

Secondly if you require only positives, filter your initial list B in a list comprehension and then iterate through it:

def Avg(B):
    mysum = 0
    pos = [i for i in B if i>0]
    for i in pos:
        mysum += i
    return mysum/len(pos)

Using the built-in sum , you can, of course, shorten this to:

def Avg(B):
    pos = [i for i in B if i>0]
    return sum(pos)/len(pos)

Just check if b in B is negative, if it is skip it. In the end you need to remember how many numbers you skipped to calculate a correct average. I used the integer variable called negatives.

def Avg(B):
    sum = 0
    negatives = 0
    for b in B:
        if b >= 0:
            sum = sum + b
        else:
            negatives += 1
    return sum/(len(B)-negatives)

Alternatively you can count the positives (it avoids the superfluous call to len and more directly expresses 'average' - the sum of the things being averaged by their number. Thanks @pvg ):

def Avg(B):
    sum = 0
    positives = 0
    for b in B:
        if b >= 0:
            sum = sum + b
            positives += 1
    return sum/positives

Anyway you should probably use another name for sum so you won't shadow sum function of the standart library.

def Avg(B):
    sum = 0
    count = 0
    for b in B:
        if b < 0:
            continue
        sum += b
        count += 1
    return sum/count

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