可以在Python中获取DFS的全局变量以返回正确的值
我正在学习使用Python实施DFS算法。 DFS将在二进制树中返回最大值,
我写了两种方法。第一个方法是Findmax函数 - 它使用返回值来跟踪树中的最大值。第二种方法是FindMax2函数 - 它使用全局变量来跟踪最大值。
我四处搜索,但无法真正理解为什么我的第二种方法不起作用 - 全局变量,max_val,不会返回正确的值,而错误msg是
UnboundLocalError: local variable 'max_val' referenced before
assignment
我在python上不是很好,所以任何帮助非常感谢。 :)这是代码。
class Node:
def __init__(self, key):
self.left = None
self.val = key
self.right = None
def inorder(self, root):
if root:
self.inorder(root.left)
print(root.val)
self.inorder(root.right)
def findMax(self, root):
if root is None:
return float('-inf')
max_lv = self.findMax(root.left)
max_rv = self.findMax(root.right)
return max(root.val, max_lv, max_rv)
max_val = float('-inf')
def findMax_2(self, root):
if root is None:
return max_val
max_val = max(max_val, root.val)
dfs(root.left)
dfs(root.right)
r = Node(5)
r.left = Node(1)
r.left.left = Node(8)
r.left.right = Node(11)
r.inorder(r)
print(r.findMax_2(r))
更新: 感谢大家的评论。我根据Ggorlen的建议修改了代码。
def findMax_2(self, root):
def dfs(node):
if node is None:
return max_val
max_val = max(max_val, node.val)
print("max_val:", max_val)
dfs(node.left)
dfs(node.right)
max_val = float('-inf')
dfs(root)
return max_val
但是我仍然有同样的错误:
Traceback (most recent call last):
File "dfs_findMax_2.py", line 56, in <module>
print("max val:", r.findMax_2(r))
File "dfs_findMax_2.py", line 44, in findMax_2
dfs(root)
File "dfs_findMax_2.py", line 38, in dfs
max_val = max(max_val, node.val)
UnboundLocalError: local variable 'max_val' referenced before assignment
我错过了什么吗?
I am learning to use Python to implement DFS algorithm. The DFS will return the max value in a binary tree
There are 2 approaches I wrote. The 1st approach is findMax function - it uses return values to track the max value in a tree. The 2nd approach is findMax2 function - it uses a global variable to track the max value.
I googled around, but couldn't really understand why my 2nd approach doesn't work - the global variable, max_val, won't return the correct value, and the error msg is
UnboundLocalError: local variable 'max_val' referenced before
assignment
I'm not very good at Python, so any help is greatly appreciated. :) Here is the code.
class Node:
def __init__(self, key):
self.left = None
self.val = key
self.right = None
def inorder(self, root):
if root:
self.inorder(root.left)
print(root.val)
self.inorder(root.right)
def findMax(self, root):
if root is None:
return float('-inf')
max_lv = self.findMax(root.left)
max_rv = self.findMax(root.right)
return max(root.val, max_lv, max_rv)
max_val = float('-inf')
def findMax_2(self, root):
if root is None:
return max_val
max_val = max(max_val, root.val)
dfs(root.left)
dfs(root.right)
r = Node(5)
r.left = Node(1)
r.left.left = Node(8)
r.left.right = Node(11)
r.inorder(r)
print(r.findMax_2(r))
Update:
Thanks for everyone's comments. I modified my code based on ggorlen's suggestion.
def findMax_2(self, root):
def dfs(node):
if node is None:
return max_val
max_val = max(max_val, node.val)
print("max_val:", max_val)
dfs(node.left)
dfs(node.right)
max_val = float('-inf')
dfs(root)
return max_val
But I still got the same error:
Traceback (most recent call last):
File "dfs_findMax_2.py", line 56, in <module>
print("max val:", r.findMax_2(r))
File "dfs_findMax_2.py", line 44, in findMax_2
dfs(root)
File "dfs_findMax_2.py", line 38, in dfs
max_val = max(max_val, node.val)
UnboundLocalError: local variable 'max_val' referenced before assignment
Did I miss anything?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
根据Ggorlen的建议,这是有效的代码。谢谢你!
Based on ggorlen's advice, here is the code that works. Thank you!
Python范围规则有一些尖锐的角落。
在类和外部功能中,
max_val
是类变量。在函数内部,它是一个词汇变量,该变量范围为函数,恰好具有相同的名称。您的错误是因为您要在分配给词汇变量之前访问词汇变量,因此Python知道您很困惑(但没有给您足够的上下文来毫无意义)。要访问函数中的类变量,您需要访问
self.max_val
。如果它确实是一个全局变量,则需要在函数中使用
全局max_val
声明。 (不是,所以不要尝试。)对于另一个功能,您需要做一个非局部max_val
。最后,由于它是一个类变量,因此可以通过类的所有实例访问。如果您希望它是实例变量,则将其分配给
self.max_val
在init
方法中,您仍然会通过self.max_val 在其他方法中。
Python scoping rules have a few sharp corners.
In the class and outside the function,
max_val
is a class variable. Inside the function it is a lexical variable scoped to the function, which just happens to have the same name. Your error is because you are accessing the lexical variable before it is assigned to, so Python knows you are confused (but didn't give enough context to unconfuse you).To access the class variable inside the function you need to access
self.max_val
.If it was truly a global variable, you'd need to have a
global max_val
declaration in the function before you do anything with it. (It isn't, so don't try it.) And in the case of one function inside another, you'd need to do anonlocal max_val
instead.And, finally, because it is a class variable, it will be accessible through all instances of the class. If you wanted it to be an instance variable instead, you'd have assigned to
self.max_val
inside of yourinit
method, and you'd still access it throughself.max_val
in other methods.