How do I find the names on the list?

Asked

Viewed 62 times

-5

Complete the function buscar(lista, animal) below, which receives two values:

  • A list of animal names.
  • The name of an animal you want to find on the list.

The function must return True if the animal exists on the list, and False otherwise.

When finishing the function, run the program and test it with some animals from the list.

Suggestions:

  • tatu (exists in the list)
  • rabbit (not listed)

Below is the code:

def buscar(lista, animal):
  pass  # comando inútil (você pode apagá-lo se quiser)
  # Complete o código faltante aqui!

# Programa principal: NÃO MODIFIQUE O CÓDIGO ABAIXO
def programa_principal():
  lista_animais = ['avestruz', 'cachorro', 'cavalo', 'gato', 'papagaio', 'tatu', 'urso', 'zebra']
  
  bicho = input('Informe um animal: ')
  while bicho != '':
      if buscar(lista_animais, bicho):
          print(bicho, 'existe na lista!')
      else:
          print(bicho, 'não existe na lista!')
      bicho = input('\nInforme um animal: ')

programa_principal()
  • 1

    Welcome to Stack Overflow in English. It seems your question contains some problems. We won’t do your college work or homework, but if you’re having difficulty somewhere specific, share your code, tell us what you’ve tried and what the difficulty is, so you increase your chances of getting a good answer. Be sure to read the Manual on how NOT to ask questions to have a better experience here.

1 answer

2

To check if an element exists in the list - or even in any object that has the method __contains__ - use the "keyword" in as follows:

def buscar(lista, animal):
    # Verifica se "animal" é um elemento que está dentro da lista.
    return animal in lista

What this "keyword" does is implicitly call the method __contains__ - which returns a boolean value - passing as argument the element to the left of in.

Knowing this, we can create a class with our own rules to validate whether or not the object has a certain element. See the situation below:

class Jogo:
    
    def __init__(self, jogador1, jogador2):
        self.__jogador1 = jogador1
        self.__jogador2 = jogador2

    def __contains__(self, jogador):
        if jogador == self.__jogador1 or jogador == self.__jogador2: return True
        else: return False

jogo = Jogo("David", "Bruno")

print("Gabriel" in jogo) # False
print("David" in jogo)   # True

In the above example, it is checked whether players Gabriel and David are in the game. In both checks, the method __contains__ is invoked, having the player name - string to the left of the in - passed to the parameter jogador method, where the element will be validated, returning True or False.

Browser other questions tagged

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