Python实现简单字典树的方法
本文实例讲述了Python实现简单字典树的方法。分享给大家供大家参考,具体如下:
#coding=utf8
"""代码实现了最简单的字典树,只支持由小写字母组成的字符串。
在此代码基础上扩展一下,就可以实现比较复杂的字典树,比如带统计数的,或支持更多字符的字典树,
或者是支持删除等操作。
"""
classTrieNode(object):
def__init__(self):
#是否构成一个完成的单词
self.is_word=False
self.children=[None]*26
classTrie(object):
def__init__(self):
self.root=TrieNode()
defadd(self,s):
"""Addastringtothistrie."""
p=self.root
n=len(s)
foriinrange(n):
ifp.children[ord(s[i])-ord('a')]isNone:
new_node=TrieNode()
ifi==n-1:
new_node.is_word=True
p.children[ord(s[i])-ord('a')]=new_node
p=new_node
else:
p=p.children[ord(s[i])-ord('a')]
ifi==n-1:
p.is_word=True
return
defsearch(self,s):
"""Judgewhethersisinthistrie."""
p=self.root
forcins:
p=p.children[ord(c)-ord('a')]
ifpisNone:
returnFalse
ifp.is_word:
returnTrue
else:
returnFalse
if__name__=='__main__':
trie=Trie()
trie.add('str')
trie.add('acb')
trie.add('acblde')
printtrie.search('acb')
printtrie.search('ac')
trie.add('ac')
printtrie.search('ac')
更多关于Python相关内容可查看本站专题:《Python字典操作技巧汇总》、《Python正则表达式用法总结》、《Python数据结构与算法教程》、《PythonSocket编程技巧总结》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python入门与进阶经典教程》及《Python文件与目录操作技巧汇总》
希望本文所述对大家Python程序设计有所帮助。