Issue
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:
- At
lineA
, thehash
is{3: 0, 2: 0}
- Then loop starts at
lineB
, the first loop,i is 0
, sotemp
is6-3
, that is3
, andhash[3]
is0
, not equal1
, so gotolineD
- Begin the loop again at
lineB
, the second loop,i is 1
, sotemp
is6-2
, that is4
, then inlineC
it executeif 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)]
Answered By - atline
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.