我的第一个python代码实践:Trie树
Trie树 不解析, 本园很多博文有提到。
直接上代码:
#coding:utf-8
'''
create on 2013-07-30
@author :HuangYanQiang
'''
LETTER_NUM=27;#组成单词的字母个数,26个字母+'-' #Trie 结构体
class Node:
def __init__(self, is_word=False):
global LETTER_NUM;
self.is_word = is_word;#是不是单词结束节点
self.prefix_count = 0;#这个前缀的单词个数
self.children = [None for child in range(LETTER_NUM)]; #Trie 结构体
class Trie:
def __init__(self):
self.head = Node();
###插入新单词
def insert(self, word):
current = self.head;
count = 0 ; for letter in word:
if (letter == '-'):
int_letter=LETTER_NUM-1;
else:
int_letter = ord(letter)-ord('a');
if(current.children[int_letter] is None):
current.children[int_letter] = Node();
current = current.children[int_letter];
count += 1;
current.prefix_count = count;
else:
current = current.children[int_letter];
current.prefix_count += 1;
current.is_word = True;
###查询单词是否存在
def search(self, word):
current = self.head;
int_letter = 0;
for letter in word:
if (letter == '-'):
int_letter=LETTER_NUM-1;
else:
int_letter = ord(letter)-ord('a'); if (current.children[int_letter] is None):
#print "int_letter = " + str(int_letter);
return False;
else:
current = current.children[int_letter];
return current.is_word;
###根据字母前缀输出所有的单词
def output(self,strPrefix):
if(strPrefix is None or strPrefix == ""):
print ("please tell me prefix letter.");
currentNode = self.head;
int_letter = 0;
for letter in strPrefix:
if (letter == '-'):
int_letter=LETTER_NUM-1;
else:
int_letter = ord(letter)-ord('a');
currentNode = currentNode.children[int_letter]; if(currentNode is not None):
if(currentNode.is_word):
print (strPrefix+"; ");
else:
return; for i in range(LETTER_NUM):
if(currentNode.children[i] is not None):
self.output(strPrefix+chr(i+ord('a'))); ################# ###读取单词列表文本构造Trie结构
class BuildTrie: def __init__(self):
self.trie = Trie();
for line in file("EnglishDict.txt"):
line = line.lower();#全部换成小写
line = line.replace('\r','').replace('\n','');#去掉结束符
isword = True;
int_letter = 0;
str_letter="abcdefghijklmnopqrstuvwxyz-ABCDEFGHIJKLMNOPQRSTUVWXYZ"
for letter in line:
if(letter not in str_letter ):
isword = False;
break;
if(isword == False):
print (line + ", it is not a word");
continue;
else:
self.trie.insert(line); if __name__=="__main__":
import doctest
doctest.testmod(); # t = Trie();
# t.insert("apple");
# t.insert("abc");
# t.insert("abandon");
# t.insert("bride");
# t.insert("bridegroom");
# t.insert("good");
# t.output("b"); bt = BuildTrie();
t = bt.trie
t.output("z"); print t.search("apple");
print t.search("fff");
print t.search("good");
print("a num:"+str(t.head.children[0].prefix_count));
print("ab num:"+str(t.head.children[0].children[1].prefix_count));
print("b num:"+str(t.head.children[1].prefix_count));
我的第一个python代码实践:Trie树的更多相关文章
- kNN算法基本原理与Python代码实践
kNN是一种常见的监督学习方法.工作机制简单:给定测试样本,基于某种距离度量找出训练集中与其最靠近的k各训练样本,然后基于这k个“邻居”的信息来进行预测,通常,在分类任务中可使用“投票法”,即选择这k ...
- 一个python代码练习
需求: 写一个用户登录窗口 验证输入的用户名和密码,若正确打印欢迎信息,输入错误三次则加入锁定名单. 锁定名单要持久化存储 # *-* coding:utf-8 *-* # Auth: wangxz ...
- 第一个python代码
# -*- coding:utf-8 -*- user = raw_input("请输入用户名") passwd = raw_input("请输入密码") if ...
- 15行python代码,帮你理解令牌桶算法
本文转载自: http://www.tuicool.com/articles/aEBNRnU 在网络中传输数据时,为了防止网络拥塞,需限制流出网络的流量,使流量以比较均匀的速度向外发送,令牌桶算法 ...
- if __name__== "__main__" 的意思(作用)python代码复用
if __name__== "__main__" 的意思(作用)python代码复用 转自:大步's Blog http://www.dabu.info/if-__-name__ ...
- 第一个python程序
一个python程序的两种执行方式: 1.第一种方式是通过python解释器: cmd->python->进入python解释器->编写python代码->回车. 2.第二种方 ...
- beamer中插入c代码,python代码的经验
下面是插入的scala代码,它与python在某些语法上类似,所在在https://github.com/olivierverdier/python-latex-highlighting下载了一个py ...
- 如何使用 Pylint 来规范 Python 代码风格
如何使用 Pylint 来规范 Python 代码风格 转载自https://www.ibm.com/developerworks/cn/linux/l-cn-pylint/ Pylint 是什么 ...
- 使用Pylint规范你的Python代码
Pylint是一个Python代码风格的检查工具,功能上类似于pychecker,默认用PEP8作为代码风格标准,它所提供的功能包括:检查代码行的长度,检查变量命名是否符合规范,检查声明的接口是否被真 ...
随机推荐
- Java设计模式06:常用设计模式之适配器模式(结构型模式)
1. Java之适配器模式(Adapter Pattern) (1)概述: 将一个类的接口转换成客户希望的另外一个接口.Adapter模式使得原本由于接口不兼容而不能一起工作的那些类,可以在一起 ...
- c++20道面试题
摘自传智播客论坛 问1:请用简单的语言告诉我C++ 是什么?答:C++是在C语言的基础上开发的一种面向对象编程语言,应用广泛.C++支持多种编程范式 --面向对象编程.泛型编程和过程化编程. 其编程领 ...
- linux 远程工具
SecureCRT SecureCRT官网地址:http://www.vandyke.com/products/securecrt/ Xmanager官方网址:http://www.netsarang ...
- 关于SWT中的表格(TableViewer类)
JFace是SWT的扩展.它提供了一组功能强大的界面组件.其中包含表格,树,列表.对话框,向导对话框等. 表格是一种在软件系统中很常用的数据表现形式.特别是基于数据库的应用系统.表格更是不可缺少的界面 ...
- 怎样安装WIN7系统
如何避免win7自动创建200M隐藏分区 1 安装win7到选择安装到哪个分区的时候,不能选择 unallocated diskspace ,也不能选 delete 已有的分区(例如C盘)安全的做法是 ...
- SSRS集成至Web
分几步进行,第一步要实现:IReportServerCredentials 接口第二步:拖入ReportViewer控件第三步:进行报表传参控制.具体如下图描述....代码部分参考下附件 using ...
- 【转】为 XmlNode.SelectNodes 加上排序功能
测试资料: <Config> <Item a='/> <Item a='/> <Item a='/> <Item a='/> <Ite ...
- postgresql 将同一个字段的值组合和将多个字段的值组合
多字段值根据连接符拼接 concat_ws(':',aaa,bbb) 单字段值根据连接符拼接 string_agg(ccc,' \r\n ') 如果要将多个字段的值拼接成一个: string_agg( ...
- 基于微软EnterpriseLib的框架(一)
1.框架模型无ORM,重点在数据库建模设计与UI框架设计上 2.多数据库支持(Enterprise Lib 默认仅支持SqlServer和Oracle,需自己扩展才能支持其他数据库,本文已扩展SQLi ...
- 原子/Atomic操作
原子/Atomic操作 一.什么是 原子/atom 这个术语用原子来表示不够准确,原子翻译自atom/atomic,其中atom在词典中的「词源/etymology」是: [Middle Engl ...