【发布时间】:2018-03-05 09:14:25
【问题描述】:
我正在尝试编写一种方法来计算 BST 中不同元素的数量。这是我的代码:
def numDistinct(root):
distinct = 0
seen = {}
def private_helper(root):
if not root: return
if root.val not in seen:
seen[root.val] = root.val
distinct += 1
private_helper(root.left)
private_helper(root.right)
private_helper(root)
return distinct
但是,它给了我错误UnboundLocalError: local variable 'distinct' referenced before assignment。我理解这个错误,但对我来说很奇怪seen 与distinct 具有相同的范围,不会引发相同的错误(即使在distinct 之前在private_helper() 中引用了它)。为了测试这一点,我将 distinct 更改为 dict 并设置它,以便我仍然可以将其用作计数器:distinct = {'count': 0}。错误停止了,我的方法开始完美运行。这里发生了什么?不同数据类型的范围有区别吗?
【问题讨论】:
-
@c3st7n 虽然这个问题提供了问题的解决方案,但我更感兴趣的是它为什么会发生,更具体地说,为什么它不会发生在 dicts 中。
-
改变一个对象(例如一个字典)与给一个变量赋值不同。没有分配 = 没问题。