Ryan_Liu
Ryan_Liu

Reputation: 279

python reference error in building trie tree

I want to build a trivial trie tree in python, and here is my code

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!! But I don't know when I insert 'd' in trie ? The code above does't just insert 'd' in trie.ref['a'].ref['b'].ref['c']

Upvotes: 2

Views: 120

Answers (1)

senshin
senshin

Reputation: 10360

You've run into a problem with mutable default arguments, I think.

In the initializer for Node, you have ref={}. But {} is a dict and hence a mutable object. As such, each call to Node() calls the initializer, which mutates the same ref dictionary.

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

Upvotes: 1

Related Questions