How to create a trie in Python

后端 未结 12 1486
别那么骄傲
别那么骄傲 2020-11-22 12:39

I\'m interested in tries and DAWGs (direct acyclic word graph) and I\'ve been reading a lot about them but I don\'t understand what should the output trie or DAWG file look

12条回答
  •  说谎
    说谎 (楼主)
    2020-11-22 13:32

    class Trie:
        head = {}
    
        def add(self,word):
    
            cur = self.head
            for ch in word:
                if ch not in cur:
                    cur[ch] = {}
                cur = cur[ch]
            cur['*'] = True
    
        def search(self,word):
            cur = self.head
            for ch in word:
                if ch not in cur:
                    return False
                cur = cur[ch]
    
            if '*' in cur:
                return True
            else:
                return False
        def printf(self):
            print (self.head)
    
    dictionary = Trie()
    dictionary.add("hi")
    #dictionary.add("hello")
    #dictionary.add("eye")
    #dictionary.add("hey")
    
    
    print(dictionary.search("hi"))
    print(dictionary.search("hello"))
    print(dictionary.search("hel"))
    print(dictionary.search("he"))
    dictionary.printf()
    

    Out

    True
    False
    False
    False
    {'h': {'i': {'*': True}}}
    

提交回复
热议问题