Leetcode的两个和错误__init __()缺少2个位置参数

时间:2018-11-11 20:04:28

标签: python constructor arguments

我正在求解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])

1 个答案:

答案 0 :(得分:0)

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())

编辑:

我在空闲状态下运行了代码。这是我从您的代码中得到的:

Idle run

但是我在网上找到了解决方案,它是这样的:

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界面中工作。