From what I understand, you want to implement an algorithm that takes all the values menores ou iguais
500 from a given list and calculate your Arithmetic Mean.
Well, you no need to create another list. Just scroll through the original list through a repeat loop for
and check that each item of the respective interaction is menor ou igual
to 500. If so, we count the times such values appear in the list - variable cont
- and accumulate the values of such variables in the variable soma
. Then we calculate the quotient between soma
and cont
.
That way, the algorithm would be:
acid_vit_lista = [100, 500, 200, 230, 400, 500, 600, 700, 900, 2000, 1100]
cont = soma = 0
for item in acid_vit_lista:
if item <= 500:
cont += 1
soma += item
media = (soma / cont)
print(f'\033[32mA media aritmética é: {media:.2f}')
Note that this algorithm goes through the list acid_vit_lista
and checks that each item in the list is menor ou igual
to 500
. Positive case, accumulates the amount of occurrences in the variable cont
and accumulates the value of each occurrence in the variable soma
.
It then calculates the média aritmética
of the respective values and then displays the value with duas
decimal places.
Observing
The arithmetic mean between N
values is the ratio of the sum of the values to the number of values, that is, the variable "soma"
divided by the variable "cont"
.
Now if you want to generalize this algorithm to calculate the arithmetic mean of all values menores ou iguais
to 500
of a any list, you can use the following algorithm:
acid_vit_lista = list(map(int, input('Digite o número de acidentes de trânsito: ').split()))
cont = soma = 0
for item in acid_vit_lista:
if item <= 500:
cont += 1
soma += item
media = (soma / cont)
print(f'\033[32mA media aritmética é: {media:.2f}')
When we run the second algorithm we receive the following message: Digite o número de acidentes de trânsito:
. Right now we must type all the values, in the same line, separated for a single space and press enter
. From that moment the algorithm will calculate the arithmetic mean of the values menores ou iguais
to 500
.
What is the difference between the first and second algorithm?
The first algorithm is capable of working with only one list, that is, the list that was previously written in the algorithm. The second algorithm, on the other hand, is capable of working with an indefinite number of lists. In this second algorithm, at each execution of the same, we can enter different values to assemble the said list.
Get values less than or equal to 500:
lista_filtrada = filter(lambda x: x <= 500, acid_vit_lista)
, average:media = sum(lista_filtrada) / len(lista_filtrada)
– Augusto Vasques