Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compute the average of all numbers in a list that are 50 or greater?

I want to return a function which gives the average of all the marks which are 50 or more. When I run my code, it always returns an empty list.

Here is what I have tried:

def get_pass_average(marks):
    average = []
    for count in marks:
        if count >= 50:
           average = sum(count) / len(count)          
    return round(average,2)

def test_get_pass_average():
    list1 = [50, 83, 26, 65, 92, 29, 77, 64]
    print('%.2f' % (get_pass_average(list1)))

Please help me to figure out the problems in my code, and the output should be 71.83.

like image 618
Chiu Chiu Avatar asked Sep 23 '18 08:09

Chiu Chiu


2 Answers

Try this:

l=[i for i in list1 if i>=50]
print(sum(l)/len(l))

Or:

from statistics import mean
l=[i for i in list1 if i>=50]
print(mean(l))

If want to condition for empty lists:

l=[i for i in list1 if i>=50]
if l:
    print(sum(l)/len(l))

Or:

from statistics import mean
l=[i for i in list1 if i>=50]
if l:
    print(mean(l))

For python 2:

print(sum(l)/len(l))

Should be:

print(float(sum(l))/float(len(l)))

And no statistics module.

Your code doesn't work because you're summing the iterator (an integer) not the list so that's why it's not working

like image 194
U12-Forward Avatar answered Oct 22 '22 06:10

U12-Forward


In addition to U9-Forward's answer, one using filter and mean:

from statistics import mean

list1 = [50, 83, 26, 65, 92, 29, 77, 64]
average = mean(filter((50).__le__, list1))
print('%.2f' % average)
like image 21
Daniel Avatar answered Oct 22 '22 06:10

Daniel