Search code examples
pythonpython-3.xdictionarykeyerror

Getting Key error while accessing dictionary element on key and not on index


I have written a below function to find the pair in a list whose sum is equal to the target:

def twoSum(nums, target):
    hash={}
    for i in nums:
        if i in hash.keys():
            continue
        hash[i]=0
    print(hash)
    for i in range(len(nums)):
        temp=target-nums[i]
        if (hash[temp]==1):
            return (nums.index(temp),i)
        else:
            hash[nums[i]]=1
            print(hash)

I have passed nums=[3,2,3] and target=6. While executing this code, I'm getting the below error:

{3: 0, 2: 0}
{3: 1, 2: 0}
Traceback (most recent call last):
File "xyz\#1_two_sum.py", line 18, in <module>
print(twoSum(nums,target))
File "xyz\#1_two_sum.py", line 10, in twoSum
if (hash[temp]==1):
KeyError: 4

I want to know where I'm making mistake.


Solution

  • For your code:

    def twoSum(nums, target):
        hash={}
        for i in nums:
            if i in hash.keys():
                continue
            hash[i]=0
        print(hash) # lineA
        for i in range(len(nums)): # lineB
            temp=target-nums[i]
            if (hash[temp]==1): # lineC
                return (nums.index(temp),i)
            else: # lineD
                hash[nums[i]]=1
                print(hash)
    

    It executes as follows:

    1. At lineA, the hash is {3: 0, 2: 0}
    2. Then loop starts at lineB, the first loop, i is 0, so temp is 6-3, that is 3, and hash[3] is 0, not equal 1, so goto lineD
    3. Begin the loop again at lineB, the second loop, i is 1, so temp is 6-2, that is 4, then in lineC it execute if hash[4]==1), give you error:

    if (hash[temp]==1):

    KeyError: 4

    In fact, I don't quite understand your logic to get the pair, see next function which could achieve your aims, just FYI:

    test.py:

    def find_pair(nums, target):
        print(list(set([(v, target-v) for i, v in enumerate(nums) if target-v in nums[i+1:]])))
    
    # some tests which different inputs
    find_pair([3, 2, 3], 6)
    find_pair([3, 2, 1], 6)
    find_pair([3, 2, 4, 1, 5], 6)
    find_pair([3, 2, 4, 1, 5, 3], 6)
    find_pair([-1, 7, 5, 3], 6)
    

    Just execute it, the output is next which find all pairs:

    [(3, 3)]

    []

    [(1, 5), (2, 4)]

    [(1, 5), (3, 3), (2, 4)]

    [(-1, 7)]