python trie implementation - global reference changing when function runs

60 Views Asked by At

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!

0

There are 0 best solutions below