Implementing a Trie to support autocomplete in Python

后端 未结 2 844
無奈伤痛
無奈伤痛 2021-02-04 17:50

I\'m trying to implement a data structure that supports autocomplete on a website. I\'ve managed to implement an iterative version of a Trie. It supports the two primary methods

2条回答
  •  太阳男子
    2021-02-04 18:19

    You could just implement a generator that iterates over the Trie according to prefix the same way as other methods do. Once you've found the node at the end of the prefix you can use recursive generator with yield from to iterate over the sub trie while keeping track of the prefix and yielding it when terminal node is found:

    class TrieNode:
        def __init__(self):
            self.end = False
            self.children = {}
    
        def all_words(self, prefix):
            if self.end:
                yield prefix
    
            for letter, child in self.children.items():
                yield from child.all_words(prefix + letter)
    
    class Trie:
        # existing methods here
        def all_words_beginning_with_prefix(self, prefix):
            cur = self.root
            for c in prefix:
                cur = cur.children.get(c)
                if cur is None:
                    return  # No words with given prefix
    
            yield from cur.all_words(prefix)
    
    trie = Trie()
    trie.insert('foobar')
    trie.insert('foo')
    trie.insert('bar')
    trie.insert('foob')
    trie.insert('foof')
    
    print(list(trie.all_words_beginning_with_prefix('foo')))
    

    Output:

    ['foo', 'foob', 'foobar', 'foof']
    

提交回复
热议问题