I solved a simple Leetcode problem (that finds two numbers in a list that sum to a target number) in Python and found it curious why when I tried to change only one line to access the hashMap my code stopped functioning because of a KeyError. But I don't understand why the 'correct' way doesn't generate a keyError.
The way that works
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
hashMap = {}
for ind, val in enumerate(nums):
busq = target - val
if busq in hashMap: #This line is the only thing that changes
return [hashMap[busq], ind]
hashMap[val] = ind
This doesn't work
def twoSum(self, nums, target):
hashMap = {}
for ind, val in enumerate(nums):
busq = target - val
if(hashMap[busq]): #This doesn't work
return [hashMap[busq], ind]
hashMap[val] = ind
CodePudding user response:
You can't access a non existing key in a python dictionary by using square brackets notation like hashmap[busq]
, instead you should check for key existence before accessing it using in
operator like in the first method.
You can also use if hashmap.has_key(busq):
to check for key existence.
CodePudding user response:
Maybe use something like this instead:
try:
return [hashMap[busq], ind]
except KeyError:
hashMap[val] = ind
When the key is not in the dict it will not return “False” but throw an error. So “if” will not work.