即使设置为全局(Python)和#x2B;我如何处理这种情况?
我有一个递归函数,它在最后计算一些答案,我必须存储这些临时答案的最大值并返回它 代码如下。即使设置为全局(Python)和#x2B;我如何处理这种情况?,python,recursion,nameerror,Python,Recursion,Nameerror,我有一个递归函数,它在最后计算一些答案,我必须存储这些临时答案的最大值并返回它 代码如下。 (如果你知道这一点,我并不担心卡丹的算法,我想知道如何做到这一点) 我得到的错误是: name错误:未定义名称“ans” 在这种情况下,如何存储最大值并返回它?因为这不起作用。您需要在与变量声明本身相同的函数中声明全局变量,因为现在您正试图为嵌套函数范围之外的变量设置全局变量 以下代码应该可以工作: class Solution: def maxSubArray(self, nums: List[
(如果你知道这一点,我并不担心卡丹的算法,我想知道如何做到这一点) 我得到的错误是:
name错误:未定义名称“ans”
在这种情况下,如何存储最大值并返回它?因为这不起作用。您需要在与变量声明本身相同的函数中声明全局变量,因为现在您正试图为嵌套函数范围之外的变量设置全局变量 以下代码应该可以工作:
class Solution:
def maxSubArray(self, nums: List[int]) -> int:
global ans
ans = nums[0]
def helper(n):
global ans
if(n == 1):
return nums[0]
temp = max(nums[n-1], nums[n-1]+helper(n-1))
ans = max(ans, temp) ### how do I do this? ###
return temp
helper(len(nums))
return and
请记住,不仅在定义变量时,还必须在要分配给变量的每个函数中添加
全局ans
。必须在第一个函数和第二个函数中添加全局ans
。
使用您的代码:
class Solution:
def maxSubArray(self, nums: List[int]) -> int:
global ans
ans = nums[0]
def helper(n):
global ans
if(n == 1):
return nums[0]
temp = max(nums[n-1], nums[n-1]+helper(n-1))
ans = max(ans, temp) ### how do I do this? ###
return temp
helper(len(nums))
return ans
这是
非本地
关键字的完美用例!
此关键字允许您引用封闭函数中的
ans
变量
解决方案(只需将全局
替换为非局部
):
因为当您第一次尝试使用它时,没有全局
ans
“此关键字允许您引用封闭函数中的ans变量。”它允许您分配给它,您可以始终仅引用它。但是,是的,这比使用全局变量错误要好得多。我将更新我的答案
class Solution:
def maxSubArray(self, nums: List[int]) -> int:
global ans
ans = nums[0]
def helper(n):
global ans
if(n == 1):
return nums[0]
temp = max(nums[n-1], nums[n-1]+helper(n-1))
ans = max(ans, temp) ### how do I do this? ###
return temp
helper(len(nums))
return ans
class Solution:
def maxSubArray(self, nums: List[int]) -> int:
ans = nums[0]
def helper(n):
nonlocal ans
if(n == 1):
return nums[0]
temp = max(nums[n-1], nums[n-1]+helper(n-1))
ans = max(ans, temp) ### how do I do this? ###
return temp
helper(len(nums))
return ans