python - 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])
解决方案
该类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 - 为什么在 Python 中使用池多处理会得到不同的结果?
- javascript - 选中复选框时更改输入的值
- javascript - Jest/node.js:自定义 console.log 输出?
- java - 修改 REST API 响应以仅包含查询参数中请求的字段
- sms - Twilio 将 SMS 转发到电子邮件和另一部手机
- javascript - 为什么文本不显示在firebase中
- php - foreach循环只返回一个值,mysqli_insert返回0
- javascript - 多次启动和停止相同的间隔
- python - 试图按下这个一次性电子邮件网站上的复制按钮
- html - 如何在 Chrome 中使用检查器时防止页面导航