find least repeated value in list

Asked

Viewed 105 times

1

I have to draw a thousand numbers between 0 and 100, and point out which numbers were more/less repeated and the highest and lowest value, but I could not find a way to show what was less drawn.

import random
lista = []
n = 1000
for y in range(n):
    num = random.randint(1, 100)
    lista.append(num)
    #print(lista)
print(f"O maior número sorteado é: {max(lista)}\nO menor número sorteado é: {min(lista)}")

1 answer

3


In statistics, the frequency (or absolute frequency) of an event i is the number nᵢ times the event occurred in an experiment or study. That is the amount of times that this value appears in sample.
Wikipedia: Frequency (statistics)

What happens is that not always will appear only a number with the lowest frequency. It may occur that one or more numbers have the same frequency.

So to find the numbers that occur least often in your list you first have to compute the frequency of each element in the list and then analyze which or which elements have the lowest frequency.

To compute the frequency of each element the method can be used list.Count(), which returns the number of times an item appears in the list and stores the result in a dictionary where keys are the list numbers and values are the respective frequencies.

To find the lowest frequency among the dictionary values you can use the builtin function min(), which returns the smallest value of an iterable, and use this value to find the keys.

import random
lista = []
n = 1000
for y in range(n):
    num = random.randint(1, 100)
    lista.append(num)
    #print(lista)
print(f"O maior número sorteado é: {max(lista)}\nO menor número sorteado é: {min(lista)}")

frequencia = {} #Dicionário onde serão contabilizadas as frequências

#Para cada elemento da lista...
for n in lista:
  if (n not in frequencia): #Se a frequência ainda não foi computada
    frequencia[n] = lista.count(n) #Conta o número de vezes que o elemento apareceu

#Obtém a menor frequência.
menorFrequencia = min(frequencia.values())

#Cria uma lista contendo os números que menos apareceram.
menosOcorreram = [k for k,v in frequencia.items() if v == menorFrequencia]

print(f'Menor frequência {menosOcorreram} com {menorFrequencia} ocorrência(s)')

Test in Repl.it.

Browser other questions tagged

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