How can I associate typed and stored values in an array to a menu option?

Asked

Viewed 53 times

1

How can I associate a range of values from 1 to 6 to each of the options in the OS menu that I have in the list? My idea is that when I type three times the number 1 for example, this counts as three votes for the Windows Server option, so in the end I can print it as the most voted poll.

I thought I’d try to solve it with a dictionary, but I’d have to type in the name of the operating system as a key every time I wanted to compute a vote

votos = []
valor = 0
mais_votado = []
maisvotado = 0
maiorpercent = 0

print('Qual o melhor sistema operacional para uso em servidores?''\n''As respostas são:''\n'
      '1 - Windows Server''\n'
      '2 - Unix''\n'
      '3 - Linux''\n'
      '4 - Netware''\n'
      '5 - Mac OS''\n'
      '6 - Outro')

valor = int(input('Insira o número correspondente a alguma das opções:'))
while 0 < valor <= 6:
    valor = int(input('Insira o número correspondente a alguma das opções:'))
    votos.append(valor)
    if valor > 6:
        valor = int(input('Valor inválido,insira um valor válido:'))
total = len(votos)
for i in range(total):
    if votos.count(i) > 1:
        mais_votado.append(i)
for i in mais_votado:
    if i > maisvotado:
        maisvotado = i
for i in votos:
    percent = (i * 100)/sum(votos)
    if percent > maiorpercent:
        maiorpercent = percent

2 answers

1


I thought I’d try to solve it with a dictionary, but I’d have to type in the name of the operating system as a key every time I wanted to compute a vote.

Actually no, with a dictionary you can use the option value as key:

opcoes = { '1': 'Windows Server', '2': 'Unix', '3': 'Linux', '4': 'Netware', '5': 'Mac OS', '6': 'Outro' }

I kept the keys as strings, because then you don’t need to convert them to numbers. Just check if what was typed is a valid key.

Then a "draft" of the code would look like this (I also added an option to interrupt the loop):

opcoes = { '1': 'Windows Server', '2': 'Unix', '3': 'Linux', '4': 'Netware', '5': 'Mac OS', '6': 'Outro' }
texto_opcoes = '\n'.join(f'{i} - {desc}' for i, desc in opcoes.items())
while True:
    voto = input(f'Qual o melhor sistema operacional para uso em servidores?\nAs respostas são:\n: {texto_opcoes} (0 para sair):')
    if voto == '0':
        break
    elif voto in opcoes: # se é uma opção válida
        # computa o voto
    else:
        print('Opção inválida')

To compute the votes, we can use a Counter, which in addition to keeping track of each option, also helps in getting the most voted, with the use of the method most_common. However, we also have to deal with tie cases, so we have to show everyone that they have the same amount of votes as the most voted:

from collections import Counter

votos = Counter()
opcoes = { '1': 'Windows Server', '2': 'Unix', '3': 'Linux', '4': 'Netware', '5': 'Mac OS', '6': 'Outro' }
texto_opcoes = '\n'.join(f'{i} - {desc}' for i, desc in opcoes.items())
while True:
    voto = input(f'Qual o melhor sistema operacional para uso em servidores?\nAs respostas são:\n{texto_opcoes} (0 para sair):')
    if voto == '0':
        break
    elif voto in opcoes: # se é uma opção válida
        votos.update([voto])
    else:
        print('Opção inválida')

mais_votado = votos.most_common(1)[0]
print(f'Mais votados (com {mais_votado[1]} votos cada):')
for opcao, qtd_votos in votos.items():
    if qtd_votos == mais_votado[1]:
        print(f'- {opcoes[opcao]} ')

That is, I composed the votes, always updating the Counter. Then I see the most voted. In case of a tie, most_common will return one of them, then I travel the Counter and print only the elements that have the same amount of votes as the most voted. Note that the keys of the Counter are the same as in the dictionary opcoes, and I kept them as strings because the fact that they are numbers is circumstantial, and this way the algorithm stays the same if you want to change the keys (for example, if they were option "a" for "Windows", "b" for "Unix", etc., simply change the dictionary keys, and the rest of the code would remain the same).

  • 1

    Thank you so much for the help,I managed to solve using this solution with even dictionaries,ended up getting more practical

-1

Well I made a very simple system but I think it delivers what you seek:

print('Qual o melhor sistema operacional para uso em servidores?''\n''As respostas são:''\n'
      '1 - Windows Server''\n'
      '2 - Unix''\n'
      '3 - Linux''\n'
      '4 - Netware''\n'
      '5 - Mac OS''\n'
      '6 - Outro')

votes = [0,0,0,0,0,0]
while True:
    vote = input('Insira o número correspondente a alguma das opções: ')
    print('')
    if vote == '1':
        votes[0] = votes[0] + 1
    elif vote == '2':
        votes[1] = votes[1] + 1
    elif vote == '3':
        votes[2] = votes[2] + 1
    elif vote == '4':
        votes[3] = votes[3] + 1
    elif vote == '5':
        votes[4] = votes[4] + 1
    elif vote == '6':
        votes[5] = votes[5] + 1

    if max(votes) == votes[0]:
        print('O sistema mais votado é Windows Server com: ', max(votes), ' Votos\n')
    elif max(votes) == votes[1]:
        print('O sistema mais votado é Unix com: ', max(votes), ' Votos\n')
    elif max(votes) == votes[2]:
        print('O sistema mais votado é Linux com: ', max(votes), ' Votos\n')
    elif max(votes) == votes[3]:
        print('O sistema mais votado é Netware com: ', max(votes), ' Votos\n')
    elif max(votes) == votes[4]:
        print('O sistema mais votado é Mac OS com: ', max(votes), ' Votos\n')
    elif max(votes) == votes[5]:
        print('O sistema mais votado é Outro com: ', max(votes), ' Votos\n')

Browser other questions tagged

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