How many times has the highest number been read?

Asked

Viewed 194 times

2

I have the following problem: the user enters with the amount of numbers to be read, later I want the largest among this quantity 'X' of numbers to be displayed and also how many times this higher value occurred.

Code so far:

i = 0
lista_num = []

qtd_num = int(input('Entre com a quantidade de números a serem lidos: '))

while i < qtd_num:
    num = int(input('Digite um número: '))
    i += 1
    lista_num.append(num)

print(f'O maior valor é: {max(lista_num)}')

How could I implement the occurrence counter of the highest value?

1 answer

2


Just use count, which returns the amount of times the element occurs in the list:

lista_num = ...
maior = max(lista_num)
print(f'O maior valor é {maior} e ele ocorre {lista_num.count(maior)} vezes')

Another option is to use a Counter:

from collections import Counter

lista_num = ...
maior = max(lista_num)
c = Counter(lista_num)
print(f'O maior valor é {maior} e ele ocorre {c[maior]} vezes')

The difference is that Counter is a dictionary containing the amount of occurrences of all elements of the list, while lista.count() returns only the amount of a single element.


Not directly related to the problem, but to read the numbers do not need this variable i, just use a range:

lista_num = []
for _ in range(qtd_num):
    lista_num.append(int(input('Digite um número: ')))

And if you want, you can also use a comprehensilist on, much more succinct and pythonic:

lista_num = [ int(input('Digite um número: ')) for _ in range(qtd_num) ]

You could also validate whether what was typed is actually a number, capturing the ValueError (which occurs case int does not receive a string that can be converted to number):

def ler_numero(msg):
    while True: # enquanto não digitar um número, pede que digite novamente
        try:
            return int(input(msg))
        except ValueError:
            print('Você não digitou um número')

qtd_num = ler_numero('Entre com a quantidade de números a serem lidos: ')
lista_num = [ ler_numero('Digite um número: ') for _ in range(qtd_num) ]

Note: the codes above assume that you have a list and from it you want to get the largest number and amount of occurrences of it.

But if you just want to read a certain amount of numbers and at the end get this information, you don’t even need the list. You can use the same loop who reads the numbers to see which one is bigger and keeping a count of the numbers read:

qtd_num = int(input('Entre com a quantidade de números a serem lidos: '))
maior = float('-inf')
cont = {}
for _ in range(qtd_num):
    num = int(input('Digite um número: '))
    if num > maior:
        maior = num
    c = cont.get(num, 0)
    cont[num] = c + 1

print(f'O maior valor é {maior} e ele ocorre {cont[maior]} vezes')

Browser other questions tagged

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