I am learning Python, and i use it to solve tasks on HackerRank. I have the problem with exercise Hash Tables: Ransom Note. I have written that code:
def checkMagazine(magazine, note):
mag_h = {}
#mag_h = {i: mag_h[i] + 1 if i in mag_h else 1 for i in magazine}
for i in magazine:
if i in mag_h:
mag_h[i] += 1
else:
mag_h[i] = 1
for i in note:
if (not i in mag_h) or (mag_h[i] < 1):
print("No")
return
else:
mag_h[i] -= 1
print("Yes")
return
When i use dictionary comprehension (commented line), my code does not pass all test, but when i use for instruction to create the dictionary, it does. Is it not equivalent? Could You tell me why?
Sorry for my English :(