Python - Find numbers larger than average

Asked

Viewed 559 times

1

I’m having trouble with the following question: Write a python function that you receive as parameter a real tuple. The function should return the average and the amount of values greater than the average.

And then I arrived at 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 amount of numbers larger than the average

3 answers

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))

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])

1

Besides the patrick’s response, you can use other libraries that can make your life easier.

In this case, Numpy can make your life much easier. Just use the numpy.Mean and the 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

Remember that these exercises are interesting to develop your ability. Try to solve them yourself :D!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.