不同数据类型的范围

问题描述 投票:1回答:1

我正在尝试编写一个计算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不会抛出相同的错误(即使它在private_helper()之前在distinct中被引用)。为了测试这一点,我将distinct更改为dict并将其设置为所以我仍然可以将它用作计数器:distinct = {'count': 0}。错误停止,我的方法开始完美运行。这里发生了什么?不同数据类型之间的范围是否存在差异?

python types scope
1个回答
0
投票

差异是因为可变性。字典是一个可变对象。查看在函数范围内调用distinct时,它首先尝试访问distinct所持有的对象,并尝试将distinct重新绑定到另一个对象。

distinct += 1
or
distinct = distinct + 1

是一样的但是在字典的情况下,你会反弹字典所拥有的名字。你改变了一个已存在的对象。

© www.soinside.com 2019 - 2024. All rights reserved.