如何解决在python中通过dict实现trie数据结构
在python中从dict实现trie,首先我试着理解别人的代码:
class Trie:
def __init__(self):
self.t = {}
def insert(self,word: str) -> None:
node = self.t
for c in word:
if c not in node:
node[c] = {}
node = node[c]
print(node)
node['-'] = True
我调用函数“插入”
d = Trie()
d.insert("word")
d.insert("welcome")
d.insert("what")
结果是
{}
{}
{}
{}
{'o': {'r': {'d': {'-': True}}}}
{}
{}
{}
{}
{}
{}
{'o': {'r': {'d': {'-': True}}},'e': {'l': {'c': {'o': {'m': {'e': {'-': True}}}}}}}
{}
{}
{}
我对结果感到困惑,尤其是非空的结果。代码 node = node[c]
如何获得这样的结果?
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。