我是 LeetCode.com 的新手,遇到了第一个问题(https://leetcode.com/problems/two-sum/solution/)。
针对上述问题提供了默认代码或模板,但正如我在其他人的解决方案中观察到的,他们将其简化为:
class Solution:
def twoSum(self, nums, target):
# ... code here ...
return [...]
Run Code Online (Sandbox Code Playgroud)
我不使用LeetCode提供的编辑器。我使用我自己的 IDE (VSCode)。每当我尝试创建自己的输入来测试我的代码时,我都会添加以下行:
x = Solution.twoSum("",[1, 7, 2], 9)
print(x)
Run Code Online (Sandbox Code Playgroud)
“ ”分配给self参数,以下列表用于nums,而9则用于target。
最初,我没有“”:
def twoSum([1, 7, 2], 9)
Run Code Online (Sandbox Code Playgroud)
所以我得到TypeError: TwoSum() Missing 1 required Positional argument: 'target'
这是人们真正测试代码的方式,通过将随机对象(在我的例子中是"")分配给self参数?或者还有其他更干净的方法吗?
我熟悉 OOP 的基础知识,所以我想也许应该有一个def __init__来初始化一些东西。然而,其他人的解决方案没有利用这一点。
说我有一个清单:
lst = [0, 0, 0, 0, 0]
Run Code Online (Sandbox Code Playgroud)
我想给索引 0 到 2 范围内的每个值加 1,所以是这样的:
lst[0:3] += 1
Run Code Online (Sandbox Code Playgroud)
但是,这是不可能的,因为我收到错误TypeError: 'int' object is not iterable。
我知道我可以使用以下循环:
for i in range(3):
lst[i] += 1
Run Code Online (Sandbox Code Playgroud)
但这需要 O(n) 时间,我希望在 O(1) 时间内一次性完成此过程。有可能这样做吗?