I'm learning python and trying to solve the two sum question from leetcode. While solving it, I wrote the below solution:
def twosumLookUp(nums, target):
complimentingPairs = []
hashtable ={}
for i in range(len(nums)):
compliment = target-nums[i]
if (compliment) in hashtable:
complimentingPairs.append([nums[i], compliment])
hashtable = hashtable.update({nums[i]: nums[i]})
return complimentingPairs
def main():
nums = [2, 7, 11, 15]
target = 9
print(twosumLookUp(nums, target))
if __name__ == '__main__':
main()
but every time when I'm executing it I'm getting
> File "\Desktop\Learning Python\Leet Code\1. Two
> Sum\TwoSumWithHashMap.py", line 7, in twosumLookUp
> if (compliment) in hashtable: TypeError: argument of type 'NoneType' is not iterable
I have tried initialling the dictionary and then using it but I still keep on getting the above error and I'm not sure what's is wrong. I looked up a solution for the above problem and came across the below code, which is always working. Can someone please guide me and let me know
What is wrong with my code?
How can I fix it (along with the docs links to read more on it)
Why does the below code works and mine don't ?
def twoSumHashing(num_arr, pair_sum): sums = [] hashTable = {} print(hashTable) for i in range(len(num_arr)): complement = pair_sum - num_arr[i] if complement in hashTable: print("Pair with sum", pair_sum,"is: (", num_arr[i],",",complement,")") hashTable[num_arr[i]] = num_arr[i] # Driver Code num_arr = [4, 5, 1, 8] pair_sum = 9 # Calling function twoSumHashing(num_arr, pair_sum)
CodePudding user response:
dict.update()
works in-place. So change
hashtable = hashtable.update({nums[i]: nums[i]})
to
hashtable.update({nums[i]: nums[i]})
Note, this will solve your error. It's up to you to decide if the result you will get with your code is the expected one.