How to verify if a book already exists

0

As I do to verify if the book already entered exists. Example:

 libros = {
        "Principito" : ["Titulo: Principito","Genero: Fantasia", "paginas: 20", "Autor: Raul", "Numero ISBN: 12312123", "Año de edicion: 1994", "Editorial: IZI"],
         "El padrino" : ["Titulo: El padrino","Genero:Ficcion", "paginas: 30", "Autor: Lopez", "Numero ISBN: 22312312", "Año de edicion: 1992", "Editorial: PIZI"]
}

I'm left with something like that but I know it's wrong. The error is already in the if but how should I put it?

 #Funcion para consultar por un libro.
 def consultar():
      print("Por cual libro desea consultar?")
      s=input()
      if (libros[s] == libros):
            print("Tenemos ese libro en la Biblioteca")
      else:
            print("No tenemos ese libro en la Biblioteca")
    
asked by P. Matias 05.11.2016 в 03:38
source

2 answers

0

There is a more optimal way to do this:

libros = {
    "Principito" : ["Titulo: Principito","Genero: Fantasia", "paginas: 20", "Autor: Raul", "Numero ISBN: 12312123", "Año de edicion: 1994", "Editorial: IZI"],
     "El padrino" : ["Titulo: El padrino","Genero:Ficcion", "paginas: 30", "Autor: Lopez", "Numero ISBN: 22312312", "Año de edicion: 1992", "Editorial: PIZI"]
}

Imagine that from the input (), we have an input parameter "text", to be able to focus on the for.

def consultar1(text="El padrino"):
    existe = 0 
    for libro in libros:
        if text == libro:
            existe = 1
    if (existe == 1):
        return True
    else:
        return False

This would be adapted to the previous answer.

def consultar2(text="El padrino"):
    if text in libros:
        return True
    else:
        return False

With this we go through all the keys only until there is a match, if there is one.

You can see how much faster it is, and the bigger your books the difference will be bigger.

%timeit -n1000 consultar1(): 1000 loops, best of 3: 623 ns per loop
%timeit -n1000 consultar2(): 1000 loops, best of 3: 302 ns per loop

Half the time with only two entries.

    
answered by 08.11.2016 / 15:19
source
0

According to what I understand you want the user to enter the name of a book and that search in the "database" which would be the arrangement. If so, the example that I leave you will serve you:

# -*- coding: utf-8 -*-
#AGREGA TU ARREGLO <-----
#Funcion para consultar por un libro.
def consultar():
      print("Por cual libro desea consultar?")
      s=raw_input()
      existe = 0 
      for libro in libros:
          if s == libro:
              existe = 1

      if (existe == 1):
            print("Tenemos ese libro en la Biblioteca")
      else:
            print("No tenemos ese libro en la Biblioteca")

consultar()
    
answered by 05.11.2016 в 04:23