jjo*_*jon 5 python patricia-trie
四处寻找尝试的 python 实现,以便我能够理解它们是什么以及它们如何工作,我遇到了 Justin Peel 的patricia trie并发现它非常有指导意义:它足够简单,对于像我这样的新手来说,可以玩它并且从中学习。
但是,我认为我不明白有些事情:
使用贾斯汀的类 patricia() 因此:
>>> p = patricia()
>>> words = ['foo','bar','baz']
>>> for x in words:
... p.addWord(x)
Run Code Online (Sandbox Code Playgroud)
我得到一个字典,看起来像这样:
>>> p._d
{'b': ['a', {'r': ['', {}], 'z': ['', {}]}], 'f': ['oo', {}]}
Run Code Online (Sandbox Code Playgroud)
addWord() 和 isWord() 按预期工作,但 isPrefix() 显示以下行为让我感到困惑:
>>> p.isPrefix('b')
True
>>> p.isPrefix('f')
True
>>> p.isPrefix('e')
False
Run Code Online (Sandbox Code Playgroud)
不错,符合预期;进而
>>> p.isPrefix('ba')
True
Run Code Online (Sandbox Code Playgroud)
也不错,但是:
>>> p.isPrefix('bal')
True
Run Code Online (Sandbox Code Playgroud)
此外:
>>> p.isPrefix('ballance')
True
>>> p.isPrefix('ballancing act')
True
Run Code Online (Sandbox Code Playgroud)
这里有什么我不明白的吗?
我相信该错误存在于您正在查看的代码的以下片段中:
if w.startswith(node[0][:wlen-i],i):
if wlen - i > len(node[0]):
i += len(node[0])
d = node[1]
return True
Run Code Online (Sandbox Code Playgroud)
它实际上应该是:
if w.startswith(node[0][:wlen-i],i):
if wlen - i > len(node[0]):
i += len(node[0])
d = node[1]
else:
return True
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3934 次 |
| 最近记录: |