首页 > 编程语言 >实现Trie树-Python

实现Trie树-Python

时间:2022-11-30 16:59:20浏览次数:39  
标签:node return Trie self current Python trie 实现

# 实现Trie树: 字典套字典
class Trie():
    def __init__(self):
        self.child = {}
    
    def insert(self, word):
        current_node = self.child
        for e in word:
            if e not in current_node:
                current_node[e] = {}
            current_node = current_node[e]
        # 插入单词结束时,给以value为'*'的标志位
        current_node['*'] = '*'
    
    def search(self, word):
        current_node = self.child
        for e in word:
            if e not in current_node:
                return False
            current_node = current_node[e]
            
        return '*' in current_node
    
    def startswith(self, prefix):
        current_node = self.child
        for e in prefix:
            if e not in current_node:
                return False
            current_node = current_node[e]
        return True
    
    
trie = Trie()
trie.insert("apple")
trie.insert("app")
trie.search("ao")
trie.startswith('apllea')

 

标签:node,return,Trie,self,current,Python,trie,实现
From: https://www.cnblogs.com/demo-deng/p/16938982.html

相关文章

  • Python中5大模块的使用教程(collections模块、time时间模块、random模块、os模块、sys
    1.模块的简单认识定义:模块就是我们把装有特定功能的代码进行归类的结果.从代码编写的单位来看我们的程序,从小到大的顺序:一条代码<语句块<代码块(函数,类)<模......
  • python-面向对象-类的封装-私有方法私有属性
    1.封装,就是把客观事物封装成抽象的类,并规定类中的数据和方法只让可信的类或对象操作。封装可分为两个层面:(1)第一层面的封装,创建类和对象时,分别创建两者的名称,只能通过类名或......
  • Python 日期(字符串格式)增加n天并返回(字符串格式)
    fromdatetimeimportdatetimefromdatetimeimporttimedeltadefdate_add(date_str,days_count=1):date_list=time.strptime(date_str,"%Y-%m-%d")y,......
  • Python3 notes
    Python3基础标识符第一个字符必须是字母表中字母或下划线_。标识符的其他的部分由字母、数字和下划线组成。标识符对大小写敏感。在Python3中,可以用中文作为变......
  • Python学习(二):字符串常用函数有哪些?
    1.检验字符串长度:len(str);a="hellopython"len(a)12a="hellopython"len(a[::2])##从头取到尾,隔一个取值的长度6 2.切割字符串:obj.split(str);a="hell......
  • SpringBoot 如何实现异步编程
    https://blog.csdn.net/m0_60028455/article/details/121650608 首先我们来看看在Spring中为什么要使用异步编程,它能解决什么问题?为什么要用异步框架,它解决什么问题?在......
  • python-解力扣提【两数相加】
    1.题目  2.无任何参考下自己的解题代码 解题思路:i和j在列表索引中循环,不相等且两数相加等于target则返回[i,j] 3.参考大神代码解题思路:1).enumerate多用于在f......
  • Abby:tableau 实现RFM
    效果: 步骤:1、创建计算时间间隔:DATEDIFF('day',MAX([销售日期]),#2017/6/6#)2、时间间隔--》行,客户购买次数(之前创建的计算)--》列3、销售金额--》大小,会员编号--》详......
  • Python-pyreqs库,python项目环境迁移(检阅所使用库)
    前言在python项目部署或是迁移时,需要对项目所使用环境也进行迁移,操作方法很多也很复杂,python中提供了pyreqs库,可对项目所使用的python库进行检索并导出为文件,可方便进行环......
  • 企业内部统一的移动平台,实现安全高效的业务移动化
    移动办公在数字时代已经司空见惯,无论是出差、办公室与项目地点来回奔波,还是因疫情而居家办公的人,都需要借助移动办公软件进行来线上办公。那么,如何提高企业员工在移动办公......