0

我正在尝试在 python 中实现一个 trie。这是我的课:

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

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

然后我创建了一个简单的函数来为 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")

问题是函数 add_contact 正在改变全局变量 trie。我猜“node”和“trie”是同一事物的不同名称,但我尝试使用 copy() 并且它根本没有用。有谁知道我该如何正确地做到这一点?谢谢!

4

0 回答 0