[工具]Trie in python3

来源:互联网 发布:触屏手套的原理知乎 编辑:程序博客网 时间:2024/05/17 15:03

Trie


# -*- coding: utf-8 -*-class Trie():    '''Trie in python3'''    def __init__(self):        self.data = {}    def insert(self, word):        ref = self.data        for char in word:            ref[char] = (char in ref) and ref[char] or {}            ref = ref[char]        ref[''] = 1     def dump(self):        return self.data    def search(self, word):        ref = self.data        for char in word:            if char in ref:                ref = ref[char]            else:                return False        return '' in ref    def trav(self, word, ref):        for char in ref:            word1 = word            if char == '':                print(word1)            else:                word1 = word1 + char                ref1 = ref[char]                self.trav(word1, ref1)    def traversal(self):        ref = self.data        self.trav('', ref)        def delete(self, word):        ref = self.data        parent = []        flag = 1        for char in word:            if char in ref:                ref = ref[char]                if len(ref) == 1:                    parent.insert(0,1)                else:                    parent.insert(0,0)            else:                flag = 0                break        if flag and ('' in ref) and 1:            i = len(parent)-1            ref = self.data            depth = 0            for t in parent:                if t == 0:                    break                else:                    depth += 1            for char in word:                if i >= depth:                    ref = ref[char]                    i -= 1                else:                    #print(word,' ',ref,' ',i,' removed!')                    del ref[char]                    return            del ref['']            #print(word,' removed!')        else:            #print(word,' not exist in dict')            return
test

def main():    a=Trie()    for w in ['我们', '我们中国', '我们的国家', '我们china', '我们中的']:        a.insert(w)    word='我们是'    a.insert(word)    if a.search(word):        print(word+' exists')    else:        print(word+' not exists')    a.delete(word)    if a.search(word):        print(word+' exists')    else:        print(word+' not exists')    a.traversal()if __name__ == '__main__':    main()



0 0
原创粉丝点击