Wizard
Wizard

Reputation: 22113

dict.pop() report an exceptional keyerror

I tried to solve the twoSum problem in leetcode Two Sum - LeetCode

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

Example:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

My solution:
1. Fix first number then to search (target -first)
2. Employ hash table to look up the index

class Solution():
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        # nums_d: {value:index} 
        nums_d = {nums[i]:i for i in range(len(nums))}
        for i in range(len(nums)):
            find = target - nums[i]
            print('find: ', find)
            nums_d.pop(nums[i]) #Avoid use an element twice
            j = nums_d.get(find)#hash table to search 
            print('j: ',j)
            if j: 
                return [i, j]
        return None  

and the testing codes

target = random.randrange(200,300)
nums = list(range(150))
nums = random.choices(nums, k=100)
solution = Solution()
print(solution.twoSum(nums, target))

It report KeyError when run it

In [131]: !python twoSum.py                                                                                                   
find:  168
j:  None
find:  183
j:  None
find:  216
j:  None
find:  163
j:  None
find:  182
j:  None
find:  169
j:  None
find:  235
j:  None
find:  169
Traceback (most recent call last):
  File "twoSum.py", line 67, in <module>
    print(solution.twoSum(nums, target))
  File "twoSum.py", line 57, in twoSum
    nums_d.pop(nums[i]) #Avoid use an element twice
KeyError: 122

I cannot find the problem with line nums_d.pop(nums[i])

Upvotes: 0

Views: 1467

Answers (1)

Nordle
Nordle

Reputation: 2981

Your dict size decreases with pop while i increases to the (original) length of the list, at some point you are going to be referencing an key which is higher than the size of the list, resulting in a KeyError.

What you want would be something like:

for i, k in enumerate(nums_d.keys()):
    # code stuff

This way you have i as the range to perform your indexing within nums, and you have k which refers to each key within nums_d, in order to use pop and avoid using an element twice.

Upvotes: 3

Related Questions