From what I understand you want to implement a function that returns both to Arithmetic Mean as to the Standard Deviation values. To solve this question you can use the following algorithm:
from math import pow, sqrt
def media_desvio_padrao(lis):
soma = sum(lis)
quant = len(lis)
avg = (soma / quant)
soma_t = 0
for item in lis:
soma_t += pow((item - avg), 2)
std = sqrt(soma_t / quant)
return avg, std
valores = [1, 2, 3, 4, 5, 6]
media, desvio_padrao = media_desvio_padrao(valores)
print(f'\033[32mA Média Aritmética é: {media:.2f}')
print(f'O Desvio Padrão é: {desvio_padrao:.2f}')
Note that in this algorithm has been implemented a function that takes as parameter a list and returns two values that are: mean and standard deviation.
When we execute this code, we receive the following outputs
A Média Aritmética é: 3.50
O Desvio Padrão é: 1.71
Details
When we execute the code the list is passed as argument to the function media_desvio_padrao
. This function calculates the sum of the values of the list (sum), the number of values of the list (Quant) and the arithmetic mean of these values (avg).
Then the list of valores
and traversed by the loop of repetition for
and, with each interaction of the photon, the variable soma_t
, which is responsible for the accumulation of the operation pow((item - avg), 2)
. The desvio padrão
.
Subsequently the function media_desvio_padrao
returns two values, who are: avg
(arithmetic mean) and std
(standard deviation).
Then the results are displayed formatted to two decimal places.
Now, imagine that you want to work with an indefinite amount of lists and values. In this case, you will need an algorithm that is able to work with multiple lists. For this situation we can use the following algorithm:
from math import pow, sqrt
def media_desvio_padrao(lis):
soma = sum(lis)
quant = len(lis)
avg = (soma / quant)
soma_t = 0
for item in lis:
soma_t += pow((item - avg), 2)
std = sqrt(soma_t / quant)
return avg, std
valores = list(map(int, input('Digite os valores: ').split()))
media, desvio_padrao = media_desvio_padrao(valores)
print(f'\033[32mA Média Aritmética é: {media:.2f}')
print(f'O Desvio Padrão é: {desvio_padrao:.2f}')
When we executed this second algorithm we received the following message: Digite os valores:
. Right now we must type all the values of the list in the same line, separated for a single space and press Enter
.
From now on all operations described above will be carried out.
Observation 1
With this code we can calculate the Média Aritmética
and the Desvio Padrão
of any lists containing values inteiros
.
Observation 2
With this code, we can enter per list, how many values we want.
Observation 3
To end inserting values into the list, simply press the button enter
.
Thank you so much! It helped a lot
– hnakashima96