【问题标题】:Scope of different data types不同数据类型的范围
【发布时间】: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。我理解这个错误,但对我来说很奇怪seendistinct 具有相同的范围,不会引发相同的错误(即使在distinct 之前在private_helper() 中引用了它)。为了测试这一点,我将 distinct 更改为 dict 并设置它,以便我仍然可以将其用作计数器:distinct = {'count': 0}。错误停止了,我的方法开始完美运行。这里发生了什么?不同数据类型的范围有区别吗?

【问题讨论】:

标签: python types scope


【解决方案1】:

差异是因为可变性。字典是一个可变对象。看看你在函数作用域内调用distinct时,它首先尝试访问distinct持有的对象,并尝试将distinct反弹到另一个对象。

distinct += 1
or
distinct = distinct + 1

都是一样的。但是在字典的情况下,您会反弹字典中的名称。你改变了一个已经存在的对象。

【讨论】:

    猜你喜欢
    • 2021-07-12
    • 2023-01-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-18
    • 2012-10-30
    • 1970-01-01
    • 2017-05-27
    相关资源
    最近更新 更多