Function within a Python dictionary

Asked

Viewed 136 times

-3

I am trying to perform an exercise where when creating a log file dictionary whose key is returned a random number between 100 and 9999 as enrollment as follows

 from datetime import date, time, datetime, timedelta  
    import random  
    def perguntar():  
     return input(' O que deseja realizar?\n' + 
                 '<I> Para inserir um usuário:  \n' +
                  '<P> Para pesquisar um usuário: \n' +
                  '<E> Para excluir um usuário: \n' +
                  '<L> Para listar um usuário: \n' +
                  '<S> Para sair: ').upper()
    
    def numero_de_matricula():
       num_matricula = random.randint(100, 9999)
    
    def inserir_dados(dicionario):
      dicionario[print('Matrícula: {}' .format(numero_de_matricula()))] = [input('Digite o login: ').upper(),
                        input('Digite o nome: ').upper(),
                         input('Digite a última data de acesso: '),
                         input('Digite a última estação acessada: ').upper()]

usuarios = {}
opcao= perguntar()
while opcao == 'I' or opcao =='P' or opcao =='E' or opcao == 'L':

  if opcao == 'I':
    
      inserir_dados(usuarios)
      print('Usuário cadastrado com sucesso: ')

No error returned, but the value of the returned key is Registration: None.

So I’d like to know if:

I am declaring and calling the Random function correctly for what I intend to do?

  • 1

    In function numero_de_matricula you did not return the selected value, only assigned in the variable num_matricula that is not used. Make a return num_matricula in this function, because without it the return of the function will always be None, which may justify this value as a dictionary key.

1 answer

1

As for the question.

No, you are not using the function correctly random.randint() and the other answers also do not make a correct use of the function.

How are enrolling students in a dictionary fatally function randint() will draw a license plate number that has already been used so there will be a key collision that implies the loss of a registered license plate.

To solve the problem do not use randint(), the problem is more complex than the use case which was designed.
What you can do is create a list with the range of values to be used as the number plate and then shuffle that list with the function random.shuffle() and with a generating function go extracting one by one, when asked a number of matricula with the built-in function next():

Example:

from random import shuffle

def matricula_gen():  
  matriculas = list(range(100, 1000))    #Cria uma lista com faixa válida de valores de matriculas.
  shuffle(matriculas)                    #Embaralha a lista.
  #Enquanto a lista matriculas não estiver vazia...
  while len(matriculas) > 0:
    yield matriculas.pop(0)              #...remove o primeiro elemento de matriculas e o retorna.

numero_de_matricula= matricula_gen()     #Cria o gerador de matriculas.
for _ in range(15):
  print(next(numero_de_matricula))       #Imprime 15 matriculas de teste.

Inserting into the question code.

The question code presents many problems:

  • The function perguntar() can be simplified.
  • The function numero_de_matricula() does not return value and if returned generates duplicate keys.
  • In function inserir_dados() you are using the function result print() which is None as key in a dictionary.
  • Your options menu is displayed only once.
  • The link of activities is not appropriate.

So I made some modifications to make your example functional and embed the answer to your question:

from datetime import date, time, datetime, timedelta  
from random import shuffle

menu = """O que deseja realizar?
<I> Para inserir um usuário:
<P> Para pesquisar um usuário:
<E> Para excluir um usuário:
<L> Para listar um usuário:
<S> Para sair: """

def matricula_gen():  
  matriculas = list(range(100, 1000))
  shuffle(matriculas)
  while len(matriculas) > 0:
    yield matriculas.pop(0)

proxima_matricula = matricula_gen()
    
def perguntar():  
  return input(menu).upper()
    
def numero_de_matricula():
  return next(proxima_matricula)

def inserir_dados(dicionario):
  try:
    dicionario[numero_de_matricula()] = [
      input('Digite o login: ').upper(),
      input('Digite o nome: ').upper(),
      input('Digite a última data de acesso: '),
      input('Digite a última estação acessada: ').upper()]
  except StopIteration:
    print("As matriculas estão esgotadas.")
    return False
  return True

usuarios = {}
while True:
  opcao = perguntar()
  if opcao == 'I':
    if inserir_dados(usuarios):
      print('Usuário cadastrado com sucesso. ')
    else:
      print('Usuário não pode ser cadastrado. ')
  elif opcao == 'P':
     pass
  elif opcao == 'E':
     pass
  elif opcao == 'L':
     pass
  else:
    print('Opção inválida.')
  • 1

    Another option is to use random.sample, then you could do something like for n in sample(range(100, 1000), 15): usar n to generate the 15 numbers without repetition

  • 1

    @hkotsubo, for sure. And it is also possible to directly shuffle a range with sample sample(rng:= range(100, 1000), len(rng)). I focused more on countering the responses by encouraging the use of randint() the AP came to accept one of the answers. Sorry I can not close all the possibilities of solution.

Browser other questions tagged

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