[英]Python: On a function that does not return anything
I was solving the Rotate Array leetcode problem:我正在解决旋转数组leetcode 问题:
Given an array, rotate the array to the right by k steps, where k is non-negative.
给定一个数组,将数组向右旋转 k 步,其中 k 为非负数。
I tested the following code on my computer (and it seems to do the required job):我在我的电脑上测试了以下代码(它似乎完成了所需的工作):
nums = [1,2,3,4,5,6,7]
k = 3
nums = nums[-k:] + nums[:len(nums)-k]
print(nums)
>> [5,6,7,1,2,3,4]
Therefore, I tried the following solution:因此,我尝试了以下解决方案:
class Solution:
def rotate(self, nums: List[int], k: int) -> None:
nums = nums[-k:] + nums[:len(nums)-k]
However, getting the following test case wrong:但是,得到以下测试用例错误:
Actually, this test case was tested successfully when I ran without defining any function (which I provided above).实际上,当我在没有定义任何函数(我在上面提供)的情况下运行时,此测试用例已成功测试。 Yet, really, it didn't work when I defined a special function to
rotate
.然而,实际上,当我定义一个特殊的函数来
rotate
时它不起作用。 Then, I concluded that I might be doing something wrong when defining the function.然后,我得出结论,我在定义函数时可能做错了什么。
nums = nums[-k:] + nums[:len(nums)-k]
just rebinds the local variable nums
, it does not mutate the original object that nums
was referring to before.只是重新绑定局部变量
nums
,它不会改变nums
之前所指的原始对象。 Do the following instead:请改为执行以下操作:
nums[:] = nums[-k:] + nums[:len(nums)-k]
Since slice assignment is a mutation on the object referred to by nums
, the rotation will affect the list object that was passed to the function.由于切片赋值是对
nums
引用的对象的一种更改,因此旋转将影响传递给函数的列表对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.