简体   繁体   English

构建特里树的Python参考错误

[英]python reference error in building trie tree

I want to build a trivial trie tree in python, and here is my code 我想在python中构建一个琐碎的trie树,这是我的代码

class Node:
    def __init__(self,ref={},num=0):
        self.ref = ref
        self.num = num

def makeTrie(node,s): 
    node.ref.setdefault(s[0],Node())
    if len(s) == 1:
        node.ref[s[0]].num += 1
        return
    makeTrie(node.ref[s[0]],s[1:])


trie = Node()
makeTrie(trie,'abcd')

print trie.ref['d'].num
print trie.ref['a'].ref['b'].ref['c'].ref['d'].num

And I am very confused,the statement print trie.ref['d'].num also have value!! 而且我很困惑,声明print trie.ref['d'].num也很有价值! But I don't know when I insert 'd' in trie ? 但是我不知道何时在trie中插入'd'吗? The code above does't just insert 'd' in trie.ref['a'].ref['b'].ref['c'] 上面的代码trie.ref['a'].ref['b'].ref['c']只是在trie.ref['a'].ref['b'].ref['c']插入'd'

You've run into a problem with mutable default arguments , I think. 我认为您在使用可变默认参数时遇到了问题。

In the initializer for Node , you have ref={} . Node的初始化程序中,您具有ref={} But {} is a dict and hence a mutable object. 但是{}dict ,因此是可变对象。 As such, each call to Node() calls the initializer, which mutates the same ref dictionary. 这样,对Node()每次调用都会调用初始化器,该初始化器将更改相同的ref字典。

Fix (I think): 解决(我认为):

class Node:
    #                      vvvv
    def __init__(self, ref=None, num=0):
        if ref is None: # <--
            ref = {} # <--
        self.ref = ref
        self.num = num

def makeTrie(node,s):
    node.ref.setdefault(s[0],Node())
    if len(s) == 1:
        node.ref[s[0]].num += 1
        return
    makeTrie(node.ref[s[0]],s[1:])

trie = Node()
makeTrie(trie,'abcd')

try:
    print(trie.ref['d'].num)
except KeyError:
    print('KeyError occurred!')
print(trie.ref['a'].ref['b'].ref['c'].ref['d'].num)

Result: 结果:

KeyError occurred!
1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM