字典树的基本操作

字典树的添加,删除以及查找,数量统计

#!/usr/bin/python
#coding: utf-8

class TrieNode(object):
    def __init__(self):
        self.is_word = False # 判断是否是单词
        self.children = [None] * 256

class Trie(object):
    def __init__(self, ):
        self.root = TrieNode()

        # 统计当前的单词数量
        self.count = 0

    def Add(self, s):
        "Add a string to this trie."
        n = len(s)
        p = self.root

        for i in range(n):
            if p.children[ord(s[i])] is None:
                new_node = TrieNode()
                if i == n - 1:
                    new_node.is_word = True
                    self.count += 1

                p.children[ord(s[i])] = new_node
                p = new_node
            else:
                p = p.children[ord(s[i])]
                if i == n - 1:
                    p.is_word = True
                    self.count += 1
                    return

    def Search(self, s):
        "Search the word in this trie."
        p = self.root

        for c in s:
            p = p.children[ord(c)]
            if p is None:
                return False

        if p.is_word == False:
            return False
        return True
    """
    删除单词的时候,只能修改 is_word 的值,不能修改存储的对应节点,
    因为判断是否是单词的时候,只是通过 is_word 的值进行判断。
    举例如下:字典树中存在两个单词:child children
    再删除child的时候,要保证不能影响children。
    """
    def Delete(self, s):
        "Delete the word in this trie."
        p = self.root

        for c in s:
            p = p.children[ord(c)]
            if p is None:
                return u"当前单词不存在!"

        if p.is_word == False:
            return u"当前单词不存在!"
        p.is_word = False
        self.count -= 1
        return u"删除成功"

    def Get_Count(self):
        return self.count

if __name__ == "__main__":
    trie = Trie()
    trie.Add('str')
    trie.Add('acb')
    trie.Add('acblde')
    trie.Add('I like Python!')
    print trie.Search('acb')
    print trie.Search('ac')
    trie.Add('ac')
    print u"当前单词的数量为:%d" % trie.Get_Count()
    print trie.Search('ac')
    print trie.Search("I like Python!")
    print trie.Search("a")
    print trie.Delete("ac")
    print trie.Search("ac")
    print u"当前单词的数量为:%d" % trie.Get_Count()


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值