0

I was tring to build a trie tree base on a word list, below is the node class defintion, self.next_trees for children of the node.

class Node(object):
    def __init__(self, charactor, tree_dict={}):
        self.charactor = charactor
        self.next_trees = tree_dict
        self.is_end = False

and build the tree use this function

def build_tree(words):
    root = Node(None)
    for word in words:
        trace = root.next_trees
        for i,c in enumerate(word):
            if c not in trace:
                trace[c] = Node(charactor=c)

                pdb.set_trace()

                if i == len(word)-1:
                    trace[c].is_end = True
                else:
                    trace = trace[c].next_trees
            else:
                trace = trace[c].next_trees
return root

each time when the codes run to the break point, the object "trace" refers to is exactly the same object "trace[c].next_trees" refer to,rather than a empty dict"{}" enter image description here

and I copy similiar codes to a new .py file and run, it won't happen again.why it happens here?(python version 2.7.12)

Pang JR
  • 3
  • 1

1 Answers1

0

You are using a mutable object as a default variable (tree_dict={}). Try doing this instead:

def __init__(self, charactor, tree_dict=None):
    if tree_dict is None:
        tree_dict = {}

The default value of tree_dict ({}) is evaluated only when the __init__ method is constructed, not when it is called. This default value is then stored and reused for every future call to __init__. This then means that all instances of Node initialized with no explicit value of tree_node will use this stored object as its tree_node, meaning that when you modify one, you modify all others as well.

jmd_dk
  • 12,125
  • 9
  • 63
  • 94