First, the reading of the 5 entries should not be done inside the while
, because you already know it will be 5 lines. The while
it is only after, to read the cases in which you will verify whether the present exists or not for each person.
To read the names and the respective gifts, you can use the multiple assignment along with the unpacking:
nome, *presentes = input().split()
So if the line is, for example, iara mochila estojo lapis
, the nome
will be iara
and presentes
will be a list containing 3 elements: the strings 'mochila'
, 'estojo'
and 'lapis'
. Of course, the way you did it works too, I just wanted to show you another alternative.
Then, just keep this in the dictionary, where the nome
is the key and presentes
, its value:
dici_presentes = {}
casos = int(input())
for i in range(casos):
nome, *presentes = input().split()
dici_presentes[nome] = presentes
while True: # loop "infinito"
entrada = input()
if entrada == 'FIM':
break
else:
nome, presente = entrada.split()
print(presente in dici_presentes[nome])
Then I start reading the test cases. If it’s "END", I interrupt the while
with break
. Otherwise, I’ll do the split
, taking the name and the gift. And finally, I use in
to check whether the presente
is on the list corresponding to nome
.
The code above prints True
and False
, but if you want to change the text, just do:
while True:
entrada = input()
if entrada == 'FIM':
break
else:
nome, presente = entrada.split()
if presente in dici_presentes[nome]:
print('Verdadeiro')
else:
print('Falso')
One detail is that the above code does not check if the name really is a dictionary key (it always assumes it is). If you have to check these cases too, just change the condition to:
if nome in dici_presentes and presente in dici_presentes[nome]:
print('Verdadeiro')
else:
print('Falso')
I mean, first I see if nome
is a key, and only then see if the presente
is on its list.
Another way is:
if presente in dici_presentes.get(nome, []):
print('Verdadeiro')
else:
print('Falso')
The get
tries to get the value of the key specified by nome
, and if not found, returns []
(an empty list). That is, if the nome
is not a dictionary key, the presente
will not be found, since the empty list has no element and therefore no presente
will be in it.
Thank you very much, I learned a lot in just one code.
– Pedro Bernardo