我试图在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。我猜那个"节点"和"特里"是同一个东西的不同名称,但我尝试使用copy(),它根本没有工作。有谁知道我怎么能正确地做到这一点?谢谢!