I have to design and implement a TwoSum class. It should support the following operations:
add- Add the number to an internal data structure.find- Find if there exists any pair of numbers which sum is equal to the value.
Here is my code:
class TwoSum(object):
dict = {}
def add(self,n):
dict[n] = n #TypeError: 'type' object does not support item assignment
def find(self,n):
for i in range(0,len(dict)+1):
if dict[i] == None:
continue
val = n - dict[i]
if dict[val] != None and val != i+1:
return True
return False
test = TwoSum()
test.add(1)
test.add(3)
test.add(5)
print(test.find(4)) # True
print(test.find(7)) # False
I got error message
TypeError: 'type' object does not support item assignment for "dict[n] = n"
Any help or suggestion? Thank you so much!
__init__, not at class level, and you need to access them throughself. - user2357112 supports Monicadict. Rename it so something likenumbers_dict- Keatinge