Python字典树 Python数据结构与算法之字典树实现方法示例

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

Python字典树 Python数据结构与算法之字典树实现方法示例

hanahimi   2021-03-28 我要评论
想了解Python数据结构与算法之字典树实现方法示例的相关内容吗,hanahimi在本文为您仔细讲解Python字典树的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:Python,数据结构,算法,字典树,下面大家一起来学习吧。

本文实例讲述了Python数据结构与算法之字典树实现方法。分享给大家供大家参考,具体如下:

class TrieTree():
  def __init__(self):
    self.root = {}
  def addNode(self,str):
    # 树中每个结点(除根节点),包含到该结点的单词数,以及该结点后面出现字母的键
    nowdict = self.root
    for i in range(len(str)):
      if str[i] not in nowdict:  # 发现新的组合方式
        nowdict[str[i]] = {'count':0,'prefix':str[:i+1]}
      nowdict = nowdict[str[i]]  # 转移到下一个结点
    nowdict['count'] += 1
  def countWord(self,str):
    # 返回输入单词在树中出现的次数
    nowdict = self.root
    for s in str:
      if s not in nowdict:
        return 0
      nowdict = nowdict[s]  # 匹配当前结点,转下一个结点
    # 到了这一步证明单词存在
    return nowdict['count']
if __name__=="__main__":
  pass
  Text = ['b','abc','abd','bcd','abcd','efg','hii','bcd']
  t = TrieTree()
  for str in Text:
    t.addNode(str)
  print t.countWord('bcd')
>>> 2

希望本文所述对大家Python程序设计有所帮助。

猜您喜欢

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们