0

I'm trying to implement a trie in python. This is my class:

class Node(object):
    children = {}
    data = 0

    def __init__(self):
        for char in letters:
            self.children[char] = None

Then I created a simple function to add a name to the trie:

#add name to the trie
def add_contact(name):
    node = trie

    for char in name:
        aux = node.children[char]

        if aux == None:
            aux = node.children[char] = Node()

        node = aux

    # mark as final node
    node.data = 1

# create global variable trie and add a contact
trie = {}
add_contact("test")

The problem is that the function add_contact is changing the global variable trie. I guess that "node" and "trie" are different names for the same thing, but I tried using copy() and it didn't worked at all. Does anyone knows how I can properly do this? Thanks!

  • Uh, did you *implement a `copy` method*? What exactly do you mean? "I tried using copy()" but "it didn't work at all" isn't an adequate problem specification... are you getting an error? There is no built-in `copy` function, and you haven't defined one for your `Node` class, so it isn't at all clear what you mean or what you expect. And yes, of course your function changes the global `trie`, you *assign* the global `trie` to the local name `node` here: `node = trie` What exactly were you expecting? – juanpa.arrivillaga Aug 28 '17 at 16:49
  • 2
    Also, head's up, your `Node` class has two class-level variables, `data` and `children`, which will be *shared among instances*, but that is **certainly not what you want**. You need those to be *instance variables*. This will lead to subtle bugs later on. – juanpa.arrivillaga Aug 28 '17 at 16:50
  • Yeah the problem was exactly what you mentioned. the children attribute was static, so it was being overwritten everytime. – Matheus Jun Ota Aug 28 '17 at 17:22

0 Answers0