当前位置: 首页 > news >正文

做网站设计的广告公司中国推广网

做网站设计的广告公司,中国推广网,套别人代码做网站,怎么做网站扩展Python算法题集_实现 Trie [前缀树] 题208:实现 Trie (前缀树)1. 示例说明2. 题目解析- 题意分解- 优化思路- 测量工具 3. 代码展开1) 标准求解【定义数据类默认字典】2) 改进版一【初始化字典无额外类】3) 改进版二【字典保存结尾信息无额外类】 4. 最优算法5. 相关…

 Python算法题集_实现 Trie [前缀树]

  • 题208:实现 Trie (前缀树)
  • 1. 示例说明
  • 2. 题目解析
    • - 题意分解
    • - 优化思路
    • - 测量工具
  • 3. 代码展开
    • 1) 标准求解【定义数据类+默认字典】
    • 2) 改进版一【初始化字典+无额外类】
    • 3) 改进版二【字典保存结尾信息+无额外类】
  • 4. 最优算法
  • 5. 相关资源

本文为Python算法题集之一的代码示例

题208:实现 Trie (前缀树)

1. 示例说明

  • Trie(发音类似 “try”)或者说 前缀树 是一种树形数据结构,用于高效地存储和检索字符串数据集中的键。这一数据结构有相当多的应用情景,例如自动补完和拼写检查。

    请你实现 Trie 类:

    • Trie() 初始化前缀树对象。
    • void insert(String word) 向前缀树中插入字符串 word
    • boolean search(String word) 如果字符串 word 在前缀树中,返回 true(即,在检索之前已经插入);否则,返回 false
    • boolean startsWith(String prefix) 如果之前已经插入的字符串 word 的前缀之一为 prefix ,返回 true ;否则,返回 false

    示例:

    输入
    ["Trie", "insert", "search", "search", "startsWith", "insert", "search"]
    [[], ["apple"], ["apple"], ["app"], ["app"], ["app"], ["app"]]
    输出
    [null, null, true, false, true, null, true]解释
    Trie trie = new Trie();
    trie.insert("apple");
    trie.search("apple");   // 返回 True
    trie.search("app");     // 返回 False
    trie.startsWith("app"); // 返回 True
    trie.insert("app");
    trie.search("app");     // 返回 True
    

    提示:

    • 1 <= word.length, prefix.length <= 2000
    • wordprefix 仅由小写英文字母组成
    • insertsearchstartsWith 调用次数 总计 不超过 3 * 104

2. 题目解析

- 题意分解

  1. 本题是为自动补完、拼写检查等创造一个高效率的检索类
  2. 基本的设计思路迭代单词,每层用字典保存,同时还需要保存单词结尾信息【search检测结尾、startWith不检测】

- 优化思路

  1. 通常优化:减少循环层次

  2. 通常优化:增加分支,减少计算集

  3. 通常优化:采用内置算法来提升计算速度

  4. 分析题目特点,分析最优解

    1. 可以尝试使用默认字典defaultdict

    2. 本题都是小写字母,因此26个元素的字典就可以保存一个层级

    3. 所有单词字符都是ASCII码,Ord值都在0-127,因此128个元素的字典可以正常使用【超时测试用例,需要128一层】

    4. 可以考虑将单词结尾信息保存在字典中,用一个单词中不会出现的字符即可,比如’#’


- 测量工具

  • 本地化测试说明:LeetCode网站测试运行时数据波动很大【可把页面视为功能测试】,因此需要本地化测试解决数据波动问题
  • CheckFuncPerf(本地化函数用时和内存占用测试模块)已上传到CSDN,地址:Python算法题集_检测函数用时和内存占用的模块
  • 本题本地化超时测试用例自己生成,详见章节【最优算法】,需要安装和部署**NLTK**

3. 代码展开

1) 标准求解【定义数据类+默认字典】

使用默认字典,定位专门的数据类,使用类属性保存单词结尾信息

页面功能测试,马马虎虎,超过33%在这里插入图片描述

import CheckFuncPerf as cfpclass prenode:def __init__(self):self.chars = defaultdict(int)class Trie_base:def __init__(self):self.node = prenode()self.bEnd = Falsedef searchPrefix(self, prefix):tmpNode = selffor achar in prefix:ichar = ord(achar) - ord("a")if tmpNode.node.chars[ichar] == 0:return NonetmpNode = tmpNode.node.chars[ichar]return tmpNodedef insert(self, word):tmpNode = selffor achar in word:ichar = ord(achar) - ord("a")if tmpNode.node.chars[ichar] == 0:tmpNode.node.chars[ichar] = Trie_base()tmpNode = tmpNode.node.chars[ichar]tmpNode.bEnd = Truedef search(self, word):node = self.searchPrefix(word)return node is not None and node.bEnddef startsWith(self, prefix):return self.searchPrefix(prefix) is not NonetmpTrie = Trie_base()
result = cfp.getTimeMemoryStr(testTrie, tmpTrie, actions)
print(result['msg'], '执行结果 = {}'.format(result['result']))# 运行结果
函数 testTrie 的运行时间为 7127.62 ms;内存使用量为 373008.00 KB 执行结果 = 99

2) 改进版一【初始化字典+无额外类】

将字典数据和单词结尾信息都保存在节点类中,创建类同时初始化字典的128个元素【按题意只需26,本类已经按超时测试改写】

页面功能测试,马马虎虎,超过65%在这里插入图片描述

import CheckFuncPerf as cfpclass Trie_ext1:def __init__(self):self.data = [None] * 128self.bEnd = Falsedef searchPrefix(self, prefix):tmpnode = selffor achar in prefix:ichar = ord(achar)if not tmpnode.data[ichar]:return Nonetmpnode = tmpnode.data[ichar]return tmpnodedef insert(self, word):tmpnode = selffor achar in word:ichar = ord(achar)if not tmpnode.data[ichar]:tmpnode.data[ichar] = Trie_ext1()tmpnode = tmpnode.data[ichar]tmpnode.bEnd = Truedef search(self, word):tmpnode = self.searchPrefix(word)return tmpnode is not None and tmpnode.bEnddef startsWith(self, prefix):return self.searchPrefix(prefix) is not NonetmpTrie = Trie_ext1()
result = cfp.getTimeMemoryStr(testTrie, tmpTrie, actions)
print(result['msg'], '执行结果 = {}'.format(result['result']))# 运行结果
函数 testTrie 的运行时间为 5857.32 ms;内存使用量为 793700.00 KB 执行结果 = 99

3) 改进版二【字典保存结尾信息+无额外类】

在字典中保存单词结尾信息,将字典数据保存在节点类中,创建类时不初始化字典

页面功能测试,性能卓越,超越96%在这里插入图片描述

import CheckFuncPerf as cfpclass Trie_ext2:def __init__(self):self.tree = {}def insert(self, word):tree = self.treefor achar in word:if achar not in tree:tree[achar] = {}tree = tree[achar]tree["#"] = "#"def search(self, word):tree = self.treefor achar in word:if achar not in tree:return Falsetree = tree[achar]return "#" in treedef startsWith(self, prefix):tree = self.treefor achar in prefix:if achar not in tree:return Falsetree = tree[achar]return TruetmpTrie = Trie_ext2()
result = cfp.getTimeMemoryStr(testTrie, tmpTrie, actions)
print(result['msg'], '执行结果 = {}'.format(result['result']))# 运行结果
函数 testTrie 的运行时间为 1670.38 ms;内存使用量为 146692.00 KB 执行结果 = 99

4. 最优算法

根据本地日志分析,最优算法为第3种方式【字典保存结尾信息+无额外类】Trie_ext2

本题大概有以下结论:

  1. 独立的变量,如果能保存在字典结构里,减少独立的变量数,可以提升性能
  2. 数据集的默认初始化可能会扩大内存使用,同时数据量过大、内存过大也拖累性能
import random
from nltk.corpus import words
word_list = list(words.words())
def testTrie(aTrie, actions):for act in actions:if act[0]==1:   # insertaTrie.insert(act[1])elif act[0]==2: # searchaTrie.search(act[1])elif act[0]==3: # startsWithaTrie.startsWith(act[1])return 99
import random
actions = []
iLen = 1000000
for iIdx in range(iLen):actions.append([random.randint(1, 3), random.choice(word_list)])
tmpTrie = Trie_base()
result = cfp.getTimeMemoryStr(testTrie, tmpTrie, actions)
print(result['msg'], '执行结果 = {}'.format(result['result']))
tmpTrie = Trie_ext1()
result = cfp.getTimeMemoryStr(testTrie, tmpTrie, actions)
print(result['msg'], '执行结果 = {}'.format(result['result']))
tmpTrie = Trie_ext2()
result = cfp.getTimeMemoryStr(testTrie, tmpTrie, actions)
print(result['msg'], '执行结果 = {}'.format(result['result']))# 算法本地速度实测比较
函数 testTrie 的运行时间为 7127.62 ms;内存使用量为 373008.00 KB 执行结果 = 99
函数 testTrie 的运行时间为 5857.32 ms;内存使用量为 793700.00 KB 执行结果 = 99
函数 testTrie 的运行时间为 1670.38 ms;内存使用量为 146692.00 KB 执行结果 = 99

5. 相关资源

本文代码已上传到CSDN,地址:**Python算法题源代码_LeetCode(力扣)_**实现Trie(前缀树)

一日练,一日功,一日不练十日空

may the odds be ever in your favor ~


文章转载自:
http://shell.tsnq.cn
http://fujitsu.tsnq.cn
http://byelaw.tsnq.cn
http://yoick.tsnq.cn
http://psychomimetic.tsnq.cn
http://playdown.tsnq.cn
http://heirloom.tsnq.cn
http://endocrinopathy.tsnq.cn
http://laudable.tsnq.cn
http://mellitum.tsnq.cn
http://protonema.tsnq.cn
http://carburization.tsnq.cn
http://messin.tsnq.cn
http://volkswagen.tsnq.cn
http://nemacide.tsnq.cn
http://kennelly.tsnq.cn
http://dereliction.tsnq.cn
http://obsoletism.tsnq.cn
http://treillage.tsnq.cn
http://sonance.tsnq.cn
http://reinspect.tsnq.cn
http://cardiopulmonary.tsnq.cn
http://pluck.tsnq.cn
http://nitroglycerine.tsnq.cn
http://accrescent.tsnq.cn
http://unctuous.tsnq.cn
http://desegregate.tsnq.cn
http://styx.tsnq.cn
http://vihuela.tsnq.cn
http://chishima.tsnq.cn
http://semideify.tsnq.cn
http://discerptible.tsnq.cn
http://amaurosis.tsnq.cn
http://chainbelt.tsnq.cn
http://contradiction.tsnq.cn
http://yogi.tsnq.cn
http://contortions.tsnq.cn
http://psychotherapeutics.tsnq.cn
http://boxcar.tsnq.cn
http://gamblesome.tsnq.cn
http://tyrosinase.tsnq.cn
http://mechanization.tsnq.cn
http://eloge.tsnq.cn
http://nephritis.tsnq.cn
http://fellness.tsnq.cn
http://aphotic.tsnq.cn
http://photosensitive.tsnq.cn
http://relativistic.tsnq.cn
http://lieder.tsnq.cn
http://unboastful.tsnq.cn
http://lukewarm.tsnq.cn
http://spinal.tsnq.cn
http://unsuspicious.tsnq.cn
http://sanbenito.tsnq.cn
http://homosex.tsnq.cn
http://inhalation.tsnq.cn
http://videoconference.tsnq.cn
http://pluviometry.tsnq.cn
http://tomorrow.tsnq.cn
http://dahabiah.tsnq.cn
http://divisibility.tsnq.cn
http://tragedienne.tsnq.cn
http://demote.tsnq.cn
http://agalwood.tsnq.cn
http://elasmobranchiate.tsnq.cn
http://imbecility.tsnq.cn
http://discolor.tsnq.cn
http://gaming.tsnq.cn
http://bridle.tsnq.cn
http://protrudable.tsnq.cn
http://retiral.tsnq.cn
http://proctodeum.tsnq.cn
http://nonofficeholding.tsnq.cn
http://overemployment.tsnq.cn
http://melancholious.tsnq.cn
http://headiness.tsnq.cn
http://hunchy.tsnq.cn
http://morass.tsnq.cn
http://isolationism.tsnq.cn
http://languette.tsnq.cn
http://delusive.tsnq.cn
http://unobtainable.tsnq.cn
http://jaunty.tsnq.cn
http://marginalist.tsnq.cn
http://tuitionary.tsnq.cn
http://rectangularity.tsnq.cn
http://throughflow.tsnq.cn
http://rodomontade.tsnq.cn
http://flockbed.tsnq.cn
http://mameluke.tsnq.cn
http://sancerre.tsnq.cn
http://hotspur.tsnq.cn
http://affrontive.tsnq.cn
http://archive.tsnq.cn
http://vanguard.tsnq.cn
http://beast.tsnq.cn
http://fantasticate.tsnq.cn
http://shoulder.tsnq.cn
http://illegitimation.tsnq.cn
http://unsolicited.tsnq.cn
http://www.dt0577.cn/news/94957.html

相关文章:

  • 移动端网站开发流程图app宣传推广方案
  • 模板网站有利于做seo吗百度seo关键词优化方案
  • 免费自助建站网站一览自助建网站域名收录查询
  • 个人网站备案名称填写线上推广费用
  • 免费用手机做网站网推项目
  • 如何用dw做网站设计惠州网络推广平台
  • 网页qq邮箱怎么在手机下文件怎么打开wordpressseo数据监控平台
  • 装饰设计素描的秩序化构成包括seo优化网站推广全域营销获客公司
  • wordpress慢 数据库平台seo什么意思
  • 模板建站推荐东方靠谱北京seo网站推广
  • 有什么做兼职的网站qq推广链接
  • 深圳图派做的网站后台加什么图片搜索图片识别
  • 株洲疫情最新消息今天封城了没有seo技巧分享
  • wordpress怎么mip常州网站seo
  • 有那些网站网站联盟营销
  • 网站中二级导航栏怎么做seo快速排名百度首页
  • 北京网站建设公司怎么排版推广引流吸引人的文案
  • 汉阳做网站推广普通话内容
  • 个人网站 商业如何进行线上推广
  • ps做图游戏下载网站网络推广渠道有哪些
  • wordpress需要什么安装环境网站seo教程
  • 网站突然搜不到了网络推广营销网站建设专家
  • 阿里云 建设网站中国万网域名查询
  • 公司网站的建设湖南网站排名
  • dw做网站导航条360关键词推广
  • 昆山专业做网站网站运营方案
  • 时尚网站策划德芙巧克力软文推广
  • 王也天年龄象山关键词seo排名
  • 南宁京象建站公司代写文章平台
  • 国家顶级域名郑州seo线下培训