python - 在 Python 中实现 Trie

标签 python data-structures

我用 Python 编写了一个 Trie 作为一个类。搜索和插入功能很清楚,但现在我尝试编写 python 函数 __str__,以便我可以在屏幕上打印它。但是我的功能不起作用!

class Trie(object):
    def __init__(self):
      self.children = {}
      self.val = None

    def __str__(self):
      s = ''
      if self.children == {}: return ' | '
      for i in self.children:
         s = s + i + self.children[i].__str__()
      return s

    def insert(self, key, val):
      if not key:
         self.val = val
         return
      elif key[0] not in self.children:
         self.children[key[0]] = Trie()
      self.children[key[0]].insert(key[1:], val)

现在如果我创建一个 Trie 对象:

tr = Trie()
tr.insert('hallo', 54)
tr.insert('hello', 69)
tr.insert('hellas', 99)

当我现在打印 Trie 时,出现了条目 hello 和 hellas 不完整的问题。

print tr
hallo | ellas | o 

我该如何解决这个问题?

最佳答案

为什么不让 str 实际上以存储的格式转储数据:

def __str__(self):
    if self.children == {}:
        s = str(self.val)
    else:
        s = '{'
        comma = False
        for i in self.children:
            if comma:
                s = s + ','
            else:
                comma = True
            s = s + "'" + i + "':" + self.children[i].__str__()
        s = s + '}'
    return s

结果是:

{'h':{'a':{'l':{'l':{'o':54}}},'e':{'l':{'l':{'a':{'s':99},'o':69}}}}}

关于python - 在 Python 中实现 Trie,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16932772/

相关文章:

java - 查找第二次出现索引最低的第一个重复元素

data-structures - 线性探测如何在不中断查找的情况下处理删除?

c - 如何删除 ':' token 之前的错误 : expected ',' , ';' 、 '}' 、 '__attribute__' 或 '=' ?

python - 对使用 Superfeedr 通过 XMPP 或 Pubsubhubbub 订阅和下载 RSS 提要感到困惑

python - 我如何知道 Python 的 unicode 函数识别的所有支持的编码

Python:在方法中解压字典

data-structures - Rust 自定义数据类型中的大小类型参数?

python - 是否可以使用 python 的 shell 中定义的函数?

python - 第二种滤除非黑色像素方式的实现

algorithm - 解决冲突的 HashMap 过程