首页 > 解决方案 > Leetcode 的两个和错误 __init__() 缺少 2 个位置参数

问题描述

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

标签: pythonconstructorarguments

解决方案


该类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 界面。


推荐阅读