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树的更多相关文章

  1. kNN算法基本原理与Python代码实践

    kNN是一种常见的监督学习方法.工作机制简单:给定测试样本,基于某种距离度量找出训练集中与其最靠近的k各训练样本,然后基于这k个“邻居”的信息来进行预测,通常,在分类任务中可使用“投票法”,即选择这k ...

  2. 一个python代码练习

    需求: 写一个用户登录窗口 验证输入的用户名和密码,若正确打印欢迎信息,输入错误三次则加入锁定名单. 锁定名单要持久化存储 # *-* coding:utf-8 *-* # Auth: wangxz ...

  3. 第一个python代码

    # -*- coding:utf-8 -*- user = raw_input("请输入用户名") passwd = raw_input("请输入密码") if ...

  4. 15行python代码,帮你理解令牌桶算法

    本文转载自: http://www.tuicool.com/articles/aEBNRnU   在网络中传输数据时,为了防止网络拥塞,需限制流出网络的流量,使流量以比较均匀的速度向外发送,令牌桶算法 ...

  5. if __name__== "__main__" 的意思(作用)python代码复用

    if __name__== "__main__" 的意思(作用)python代码复用 转自:大步's Blog  http://www.dabu.info/if-__-name__ ...

  6. 第一个python程序

    一个python程序的两种执行方式: 1.第一种方式是通过python解释器: cmd->python->进入python解释器->编写python代码->回车. 2.第二种方 ...

  7. beamer中插入c代码,python代码的经验

    下面是插入的scala代码,它与python在某些语法上类似,所在在https://github.com/olivierverdier/python-latex-highlighting下载了一个py ...

  8. 如何使用 Pylint 来规范 Python 代码风格

    如何使用 Pylint 来规范 Python 代码风格 转载自https://www.ibm.com/developerworks/cn/linux/l-cn-pylint/   Pylint 是什么 ...

  9. 使用Pylint规范你的Python代码

    Pylint是一个Python代码风格的检查工具,功能上类似于pychecker,默认用PEP8作为代码风格标准,它所提供的功能包括:检查代码行的长度,检查变量命名是否符合规范,检查声明的接口是否被真 ...

随机推荐

  1. ADC及DA的头文件复析

    /************************************************************* ADC12,,,,这么多的定义,搞得我都昏死啦,抽出来可能好几一些..** ...

  2. hdu 1095 A+B for Input-Output Practice (VII)

    A+B for Input-Output Practice (VII) Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32 ...

  3. HTTPS协议学习总结

    目录 一:什么是HTTPS协议?二:客户端与服务端如何建立HTTPS协议连接?三:证书.加密协议.信息摘要.签名算法概念解释与关系梳理四:低版本操作系统作为客户端发送HTTPS失败分析五:参考资料   ...

  4. jQuery-对Select的操作

    语法解释: $("#select_id").change(function(){//code...}); //为Select添加事件,当选择其中一项时触发 var checkTex ...

  5. PHP之数组遍历

    数组在PHP中是一个非常强大的武器,用起来方便.容易,由于使用起来异常灵活,用它就可以实现数据结构中的链表.栈.队列.堆以及所谓的字典.集合等,也可以转换成XML格式. 1.使用for for语句遍历 ...

  6. webform处理过程

    一.post/get传值注意几点 post提交的时候,只有写了name属性且没有写disable=true表单元素(input,select,textarea)才会被提交. 如果不确定是get还是po ...

  7. linux字符设备驱动学习笔记(一):简单的字符设备驱动

    最近在鼓捣lnux字符设备驱动,在网上搜集的各种关于linux设备驱动的代码和注释,要么是针对2.4的,要么是错误百出,根本就不能运行成功,真希望大家在发博客的时候能认真核对下代码的正确性,特别是要把 ...

  8. 使用Linq 来解决Datatable 去除数据重复

    在这也说明下,除此之外还可以通过 DataView 的方式来处理,当个人觉得这有点不好用.这里就不多作说明了 代码比较简单,直接看代码 using System; using System.Colle ...

  9. 01线性表顺序存储_List--(线性表)

    #include "stdio.h" #include "stdlib.h" #include "io.h" #include " ...

  10. OpenJudge / Poj 2141 Message Decowding

    1.链接地址: http://poj.org/problem?id=2141 http://bailian.openjudge.cn/practice/2141/ 2.题目: Message Deco ...