当前位置:Gxlcms > Python > Python实现简单字典树的方法介绍

Python实现简单字典树的方法介绍

时间:2021-07-01 10:21:17 帮助过:51人阅读

本文实例讲述了Python实现简单字典树的方法。分享给大家供大家参考,具体如下:

  1. #coding=utf8
  2. """代码实现了最简单的字典树,只支持由小写字母组成的字符串。
  3. 在此代码基础上扩展一下,就可以实现比较复杂的字典树,比如带统计数的,或支持更多字符的字典树,
  4. 或者是支持删除等操作。
  5. """
  6. class TrieNode(object):
  7. def __init__(self):
  8. # 是否构成一个完成的单词
  9. self.is_word = False
  10. self.children = [None] * 26
  11. class Trie(object):
  12. def __init__(self):
  13. self.root = TrieNode()
  14. def add(self, s):
  15. """Add a string to this trie."""
  16. p = self.root
  17. n = len(s)
  18. for i in range(n):
  19. if p.children[ord(s[i]) - ord('a')] is None:
  20. new_node = TrieNode()
  21. if i == n - 1:
  22. new_node.is_word = True
  23. p.children[ord(s[i]) - ord('a')] = new_node
  24. p = new_node
  25. else:
  26. p = p.children[ord(s[i]) - ord('a')]
  27. if i == n - 1:
  28. p.is_word = True
  29. return
  30. def search(self, s):
  31. """Judge whether s is in this trie."""
  32. p = self.root
  33. for c in s:
  34. p = p.children[ord(c) - ord('a')]
  35. if p is None:
  36. return False
  37. if p.is_word:
  38. return True
  39. else:
  40. return False
  41. if __name__ == '__main__':
  42. trie = Trie()
  43. trie.add('str')
  44. trie.add('acb')
  45. trie.add('acblde')
  46. print trie.search('acb')
  47. print trie.search('ac')
  48. trie.add('ac')
  49. print trie.search('ac')

更多Python实现简单字典树的方法介绍相关文章请关注PHP中文网!

人气教程排行