[英]Even after declaring 'i' as global variable, it shows 'i' is not defined
[英]variable not defined even after setting as global (Python) + How do I approach such cases?
我有一個遞歸 function 最后計算一些答案,我必須存儲這些臨時答案的最大值並返回它。
代碼如下。
(如果你知道這一點,我不擔心 Kadane 的算法,我想知道如何完成這項工作)
class Solution:
def maxSubArray(self, nums: List[int]) -> int:
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
我得到的錯誤是: NameError: name 'ans' is not defined
在這種情況下如何存儲最大值並返回它? 因為這不起作用。
這是nonlocal
關鍵字的完美用例! 此關鍵字允許您引用封閉 function 中的ans
變量。
解決方案(只需將global
替換為nonlocal
):
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
您需要在與變量聲明本身相同的 function 中聲明一個全局變量,因為現在您正嘗試為嵌套函數的 scope 之外的變量設置全局變量。
以下代碼應該可以工作:
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
請記住,您必須不僅在定義變量時放置global ans
,而且在您希望分配給變量的每個 function 中。
您必須在第一個 function 和第二個中添加兩次global 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
許多人已經回答了您需要使用非本地而不是全局。 讓我試着解釋一下為什么你需要這樣做。
“非本地”表示變量“既不是本地也不是全局”,即變量來自封閉的命名空間(通常來自嵌套 function 的外部 function,因為它恰好是您的情況)
為了解釋非本地和全局之間的區別,我想說非本地變量必須已經綁定在封閉的命名空間中(否則會引發語法錯誤),而本地 scope 中的全局聲明不需要變量預先綁定(如果變量未預先綁定,它將在全局命名空間中創建一個新綁定)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.