我正在解决leetcode的两个和,并且得到错误__init__() missing 2 positional arguments
这是我的代码:
class Solution(object):
def __init__(self, nums, target):
self.nums = nums
self.target = target
def twoSum(self):
for i in range(0, len(self.nums)):
j = self.target-self.nums[i]
for a in range(i+1,len(self.nums)):
if self.nums[a]==j:
return "(%d, %d)" % (self.nums[i], self.nums[a])
最佳答案
Solution
类可能缺少实例化的数组和目标。
您可以这样:
class Solution(object):
def __init__(self, nums, target):
self.nums = nums
self.target = target
def twoSum(self):
for i in range(0, len(self.nums)):
j = self.target-self.nums[i]
for a in range(i+1,len(self.nums)):
if self.nums[a]==j:
return "(%d, %d)" % (self.nums[i], self.nums[a])
nums = [1,2,3,4,5,6] # Array of numbers
target = 7 # Target
s = Solution(nums, target)
print(s.twoSum())
编辑:
我在空闲状态下运行代码。这是我为您的代码得到的:
但是我在网上找到了解决方案,结果如下:
class Solution:
# @return a tuple, (index1, index2)
def twoSum(self, num, target):
length = len(num)
# use dict: value: index + 1
# since there is only one solution, the right value must not be duplicated
dic = {}
for i in range(0, length):
val = num[i]
if (target - val) in dic:
return (dic[target - val], i + 1)
dic[val] = i + 1
# test code
num=[2, 7, 11, 15]
t= 26
s = Solution()
print(s.twoSum(num, t))
该解决方案可在LeetCode界面中使用。
关于python - Leetcode的两个和错误__init __()缺少2个位置参数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53252712/