我对下面的 trie 数据结构的实现有两个疑问。
疑点1:
我很难理解 trie 中的插入函数。这是插入词功能:
def add(self, word):
cur = self.head
for ch in word:
if ch not in cur:
cur[ch] = {}
cur = cur[ch]
# * denotes the Trie has this word as item
# if * doesn't exist, Trie doesn't have this word but as a path to longer word
cur['*'] = True
为什么 if 语句之后会启动一个空字典?
另外,cur = cur[ch]
的意义是什么? ?
请帮助我理解 if
中的这些行代码中的声明。
疑点2:
我正在尝试打印特里树中存在的所有节点,但它打印为像 <__main__.Trie object at 0x7f655de1c9e8>
这样的对象。有人可以帮我打印特里树的节点吗?
下面是代码。
class Trie:
head = {}
def add(self, word):
cur = self.head
for ch in word:
if ch not in cur:
cur[ch] = {}
cur = cur[ch]
# * denotes the Trie has this word as item
# if * doesn't exist, Trie doesn't have this word but as a path to longer word
cur['*'] = True
def search(self, word):
cur = self.head
for ch in word:
if ch not in cur:
return False
cur = cur[ch]
if '*' in cur:
return True
else:
return False
dictionary = Trie()
dictionary.add("hi")
dictionary.add("hello")
print((dictionary)) # <__main__.Trie object at 0x7f655de1c9e8>
最佳答案
1) if 语句是检查给定字符在当前深度是否还没有自己的字典,然后创建一个空字典。 cur = cur[ch]
就是将cur的深度加1,试图找到放置word
的地方
2) 要显示 Trie 的内容,请在 Trie 中添加 __ str__ 方法。
例如:
def __str__(self):
#code
关于python - 无法在 Python 中打印 Trie 中的节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59367702/