How to know how many times the highest value was read (without list)?

Asked

Viewed 48 times

0

I am doing an exercise where I must print the highest value of the numbers typed and how many times this higher value was typed.

I tried to put the qnt += 1 but it’s not working.

qnt = 0
num_lidos = int(input('Digite a quantidade de números: '))

num = int(input('\nDigite o valor: '))
if num >= 0:
    maior = num
    for num in range(1, num_lidos):
        num = int(input('Digite o valor: '))
        if num > maior:
            maior = num
            qnt += 1
    print(f'Maior valor = {maior}')
    print(f'Quantidade de vezes que o maior número foi lido: {qnt}')
else:
    print('Erro: Valor negativo.')

1 answer

1


I took the check if it’s negative, because it either does it right or it doesn’t, and the statement posted in the question doesn’t talk about it and that part has nothing to do with reported problem, so I took it. For the same reason I did not put the error check if the person did not enter a number.

The error is that you should only add in the amount of entries that are exactly higher if this value is equal to the greater, not when you find a new value as greater. When you think that value which is a new higher, then the count you were doing has no more validity because it now has a new higher value, then starts counting again. If it’s smaller keep doing nothing extra.

The ideal is not to reuse the loop variation, but in this case there is no difference. In fact this case may not even be to use a for and stay in the while, but I won’t even touch it because in Python people think it’s sacrilegious to use while, that is, by religion.

num_lidos = int(input('Digite a quantidade de números: '))
maior = 0
qnt = 0
for num in range(0, num_lidos):
    num = int(input('Digite o valor: '))
    if num > maior:
        maior = num
        qnt = 1
    elif num == maior:
        qnt += 1
print(f'Maior valor = {maior}')
print(f'Quantidade de vezes que o maior número foi lido: {qnt}')

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

  • Understood, thank you very much! I was discarding the higher value count whenever I found a new one, and really thank you for explaining how to fix :)

  • 1

    No, you were counting how many major changes happened.

Browser other questions tagged

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