python - 无法在 Python 中打印 Trie 中的节点

标签 python dictionary data-structures trie

我对下面的 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/

相关文章:

python - 仅接受 5 秒内输入的输入值的代码是什么?

python - 在 python 中检测字典数组中重复键值的方法?

python - 如何使用python动态地将不一致的字典转换为.ini?

c - Trie执行效率

python - PythonOperator 的运行时配置

python - Pandas :如果预定义列表中不存在,则将列值替换为空

java - 成对交换节点

c++ - C++-代码优化

python - 如何反转 python 中 numpy float 列表的列表中的每个元素?

c# - 如何使用 Int 删除作为 Double 的 Dictionary 行?