帕特里夏尝试的python实现

标签 python patricia-trie

为了了解它们是什么以及它们是如何工作的,我四处寻找 tries 的 python 实现,我遇到了 Justin Peel 的 patricia trie并发现它非常有启发性:对于像我这样的新手来说,它足够简单明了,可以尝试并从中学习。

但是有些事情我觉得我不明白:

因此使用 Justin 的类 patricia():

>>> p = patricia()
>>> words = ['foo','bar','baz']
>>> for x in words:
...     p.addWord(x)

我得到一个 trie 字典,看起来像这样:

>>> p._d
{'b': ['a', {'r': ['', {}], 'z': ['', {}]}], 'f': ['oo', {}]}

addWord() 和 isWord() 按预期工作,但 isPrefix() 显示了以下让我感到困惑的行为:

>>> p.isPrefix('b')
True
>>> p.isPrefix('f')
True
>>> p.isPrefix('e')
False

不错,符合预期;然后

>>> p.isPrefix('ba')
True

也不错,但是:

>>> p.isPrefix('bal')
True

此外:

>>> p.isPrefix('ballance')
True
>>> p.isPrefix('ballancing act')
True

这里有什么我不明白的?

最佳答案

我认为该错误存在于您正在查看的以下代码片段中:

       if w.startswith(node[0][:wlen-i],i):
            if wlen - i > len(node[0]):
                i += len(node[0])
                d = node[1]
            return True

实际上应该是:

       if w.startswith(node[0][:wlen-i],i):
            if wlen - i > len(node[0]):
                i += len(node[0])
                d = node[1]
            else:
                return True

关于帕特里夏尝试的python实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3121916/

相关文章:

python - 我无法让我的代码迭代 x -= 1

python - 如何在python中将数组字符串转换为数组

c - nedtries 的作者用 "in-place"表示什么?

c++ - 在基数树/patricia trie 中进行前缀搜索

python - BeautifulSoup 查找非官方 HTML 标签/属性

python - 在 Python 中使用 Matplotlib 缩放 y 轴

python - 如何在调用 dos2unix 以验证 checkin 文件的 SVN 中实现预提交 Hook 脚本

data-structures - Patricia Trie 用于快速检索 IPv4 地址和卫星数据

java - 为什么PatriciaTrie中无法访问 `floorEntry`等方法?