我必须设计并实现一个TwoSum类。它应该支持以下操作:
add-将数字添加到内部数据结构中。
find-查找是否存在任何一对数字,其总和等于该值。
这是我的代码:
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
我收到错误讯息
TypeError:“类型”对象不支持“ dict [n] = n”的项目分配
有什么帮助或建议吗?非常感谢!
参考方案
这里有很多问题,我会尽力一一解决
数据结构
dict = {}
这不仅会覆盖python的字典(请参见mgilson的评论)