Calculate arithmetic mean of a vector

Asked

Viewed 2,857 times

0

import numpy as np

matriz = []
medias = []
alunos=1

while True:  
    print("Informe o número do aluno ou um valor negativo para terminar:")
    valor=int(input('Digite o número do aluno: '))
    if valor<0:
        break
    else:
        alunos=1
        linha=[valor]
        media1=[]
        media2=[]
        media3=[]
        media4=[]
        media5=[]
        media6=[]

        for i in range(0,3,1): #Notas disciplina 1
            n1=float(input("Informe as notas da disciplina 1: "))
            linha.append(n1)
            media1.append(n1)
        media1.mean()
        print(media1)
  • Its object media1 is a Python list, which does not have a method called mean. What you need is not media = np.mean(media1)?

  • Exactly! Thank you very much!

1 answer

0


Solution #1: Using sum() and len()

vetor = [ 1, 3, 5, 7, 9, 2, 4, 6, 8, 0 ]
print( sum(vetor) / float(len(vetor)) )

Solution #2: Using lambda

vetor = [ 1, 3, 5, 7, 9, 2, 4, 6, 8, 0 ]
print( reduce(lambda x, y: x + y, vetor) / float(len(vetor)) )

Solution #3: Module statistics

from statistics import mean
vetor = [ 1, 3, 5, 7, 9, 2, 4, 6, 8, 0 ]
print( mean(vetor) )

Solution #4: Module numpy:

import numpy as np
vetor = [ 1, 3, 5, 7, 9, 2, 4, 6, 8, 0 ]
print( np.mean(vetor) )

Exit:

4.5

Browser other questions tagged

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