• linkedu视频
  • 平面设计
  • 电脑入门
  • 操作系统
  • 办公应用
  • 电脑硬件
  • 动画设计
  • 3D设计
  • 网页设计
  • CAD设计
  • 影音处理
  • 数据库
  • 程序设计
  • 认证考试
  • 信息管理
  • 信息安全
菜单
linkedu.com
  • 网页制作
  • 数据库
  • 程序设计
  • 操作系统
  • CMS教程
  • 游戏攻略
  • 脚本语言
  • 平面设计
  • 软件教程
  • 网络安全
  • 电脑知识
  • 服务器
  • 视频教程
  • vbs
  • DOS/BAT
  • hta/htc
  • python
  • perl
  • VBA
  • ColdFusion
  • ruby
  • PowerShell
  • Lua
  • Golang
  • linux shell
您的位置:首页 > 脚本语言 >python > Python实现简单字典树的方法

Python实现简单字典树的方法

作者: 字体:[增加 减小] 来源:互联网

通过本文主要向大家介绍了python 字典树,python 字典,python 字符串转字典,python 字典排序,python字典添加元素等相关知识,希望对您有所帮助,也希望大家支持linkedu.com www.linkedu.com

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

#coding=utf8
"""代码实现了最简单的字典树,只支持由小写字母组成的字符串。
在此代码基础上扩展一下,就可以实现比较复杂的字典树,比如带统计数的,或支持更多字符的字典树,
或者是支持删除等操作。
"""
class TrieNode(object):
  def __init__(self):
    # 是否构成一个完成的单词
    self.is_word = False
    self.children = [None] * 26
class Trie(object):
  def __init__(self):
    self.root = TrieNode()
  def add(self, s):
    """Add a string to this trie."""
    p = self.root
    n = len(s)
    for i in range(n):
      if p.children[ord(s[i]) - ord('a')] is None:
        new_node = TrieNode()
        if i == 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')]
        if i == n - 1:
          p.is_word = True
          return
  def search(self, s):
    """Judge whether s is in this trie."""
    p = self.root
    for c in s:
      p = p.children[ord(c) - ord('a')]
      if p is None:
        return False
    if p.is_word:
      return True
    else:
      return False
if __name__ == '__main__':
  trie = Trie()
  trie.add('str')
  trie.add('acb')
  trie.add('acblde')
  print trie.search('acb')
  print trie.search('ac')
  trie.add('ac')
  print trie.search('ac')

</div>

更多关于Python相关内容可查看本站专题:《Python字典操作技巧汇总》、《Python正则表达式用法总结》、《Python数据结构与算法教程》、《Python Socket编程技巧总结》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python入门与进阶经典教程》及《Python文件与目录操作技巧汇总》

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

</div>

您可能想查找下面的文章:

  • Python实现简单字典树的方法
  • Python实现简单字典树的方法

相关文章

  • 深入浅析Python中join 和 split详解(推荐)
  • Django中的CACHE_BACKEND参数和站点级Cache设置
  • python3.5实现socket通讯示例(TCP)
  • python中循环语句while用法实例
  • python daemon守护进程实现
  • MySQL中表的复制以及大型数据表的备份教程
  • Python中第三方库Requests库的高级用法详解
  • 在Python的Django框架中用流响应生成CSV文件的教程
  • Python使用代理抓取网站图片(多线程)
  • Python基于sftp及rsa密匙实现远程拷贝文件的方法

文章分类

  • vbs
  • DOS/BAT
  • hta/htc
  • python
  • perl
  • VBA
  • ColdFusion
  • ruby
  • PowerShell
  • Lua
  • Golang
  • linux shell

最近更新的内容

    • 在Python中处理列表之reverse()方法的使用教程
    • Python中的数据对象持久化存储模块pickle的使用示例
    • python中zip和unzip数据的方法
    • python采用django框架实现支付宝即时到帐接口
    • Python 基于Twisted框架的文件夹网络传输源码
    • Python中subprocess模块用法实例详解
    • 详解Python中的__new__、__init__、__call__三个特殊方法
    • 比较详细Python正则表达式操作指南(re使用)
    • Python中的jquery PyQuery库使用小结
    • Python 登录网站详解及实例

关于我们 - 联系我们 - 免责声明 - 网站地图

©2020-2025 All Rights Reserved. linkedu.com 版权所有