python - python中函数内变量的范围
问题描述
在尝试解决 leetcode 上的问题时,我遇到了一个错误“在赋值之前引用了局部变量”。下面我给出了整个代码(代码本身的逻辑不是我的问题)。我已经在外部函数中定义了变量。我在某处读到,在 python 中,变量的范围以这种方式工作 - 首先在本地搜索变量,然后在外部函数(如果有的话)中搜索,然后是全局的。在我的代码中,不存在局部变量“total”,但在外部函数中定义了一个。我对变量范围的理解是错误的吗?另外,我在另一个问题中使用了类似的东西,但不是整数,而是使用列表,它仅在外部函数中类似地定义,并附加在内部函数中。在这种情况下,没有发生此类错误。我在这里做错了什么?非常感谢任何澄清。
class Solution:
def pathSum(self, root: TreeNode, sum: int) -> int:
total = 0
if root is None:
return 0
def helper(root, sum, rem):
if root is None:
return
if root.val == rem:
total += 1
if root.left is not None:
helper(root.left, sum, sum - root.val)
if root.right is not None:
helper(root.right, sum, sum - root.val)
return
helper(root, sum, sum)
return total
'''
解决方案
要解决此问题,请使用nonlocal
声明:
class Solution:
def pathSum(self, root: TreeNode, sum: int) -> int:
total = 0
if root is None:
return 0
def helper(root, sum, rem):
nonlocal total
if root is None:
return
if root.val == rem:
total += 1
if root.left is not None:
helper(root.left, sum, sum - root.val)
if root.right is not None:
helper(root.right, sum, sum - root.val)
return
helper(root, sum, sum)
return total
本质上,total += 1
隐式告诉 Python 这total
是一个局部变量。
看看这个答案
推荐阅读
- java - Shell 排序比较和交换计数
- c - 如何使用 execle() 为 /bin/login 传递环境变量?
- java - 在 Android 应用程序包名称中使用特殊字符
- php - Git Branch结帐后未将Laravel 5.8会话写入cookie
- json - json-xcode/swift 遇到问题
- r - R 平均值,如果基于条件(等级)
- clojure - 如何使中间件仅在`:swagger {:deprecated true}`时放置响应标头?
- php - 将自定义计费数据添加到 Woocommerce 管理订单中的计费格式地址
- powershell - Powershell 太快返回退出代码
- jupyter-notebook - 有没有办法在 Jupyter Notebooks 上进行认证?或以可编辑模式共享笔记本?