Trie树的插入查找和前缀查找

# a={'1':{'01':{'*'},'02':'&'},2:{}}
# print(a['1'])
class Trie(object):
    def __init__(self):
        self.root={}
        self.end_of_word='#'

    def insert(self,world):
        node=self.root
        for i in world:
            node=node.setdefault(i,{})
        node[self.end_of_word]=self.end_of_word
#确认是不是在树里并且是完整的单词
    def find(self,world):
        node=self.root
        for i in world:
            if i not in node:
                return False
            node=node[i]
        return self.end_of_word in node
#确认是不是在树里的前缀
    def findStart(self,world):
        node=self.root
        for i in world:
            if i not in node:
                return False
            node=node[i]
        return True

if __name__=='__main__':
    A=Trie()
    A.insert('abcd')
    print(A.root)
    print(A.findStart('b'))

你可能感兴趣的:(Python)