Python - Find the number of numbers greater than the average

1

I have difficulty with the following question: Write a python function that receives as a parameter a real tuple. The function should return the average and the amount of values greater than the average.

And then I came up with the following result:

def somar_elementos(lista):

     soma = 0

     media = 0

     for numero in lista:

       soma += numero

       media = soma / numero

     return media

a=(5, 10, 6, 8)

print(somar_elementos(a))

However, I do not know how to continue from here to find the number of numbers greater than the average

    
asked by anonymous 12.05.2018 / 20:40

3 answers

1

This should help you:

def somar_elementos(lista):
  media = sum(lista) / len(lista)
  return media, len([n for n in lista if n > media])
    
12.05.2018 / 21:58
1

I believe that's what you want.

def somar_elementos(lista):

     soma = 0

     for numero in lista:
          soma += numero

     media = soma / len(lista)

     maiores=[]

     for i in lista:
          if i >= media:
               maiores.append(i)

     return media, maiores

a=(5, 10, 6, 8)

print(somar_elementos(a))
    
12.05.2018 / 21:37
1

In addition to Patrick's answer , you can use other libraries that can make life easier for you.

In this case, Numpy can make life much easier for you. Just use numpy.mean and numpy.size

import numpy as np.
# Pega a lista como você esta antes.    

def somar(lisnp):

  lisnp=np.array(lista)
  return lisnp.mean(),lisnp[lisnp>lisnp.mean()].size

It is worth remembering that these exercises are interesting to develop your ability. Try to solve them alone: D!

    
12.05.2018 / 22:10