How to create a trie in Python

后端 未结 12 1409
别那么骄傲
别那么骄傲 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:14

    Modified from senderle's method (above). I found that Python's defaultdict is ideal for creating a trie or a prefix tree.

    from collections import defaultdict
    
    class Trie:
        """
        Implement a trie with insert, search, and startsWith methods.
        """
        def __init__(self):
            self.root = defaultdict()
    
        # @param {string} word
        # @return {void}
        # Inserts a word into the trie.
        def insert(self, word):
            current = self.root
            for letter in word:
                current = current.setdefault(letter, {})
            current.setdefault("_end")
    
        # @param {string} word
        # @return {boolean}
        # Returns if the word is in the trie.
        def search(self, word):
            current = self.root
            for letter in word:
                if letter not in current:
                    return False
                current = current[letter]
            if "_end" in current:
                return True
            return False
    
        # @param {string} prefix
        # @return {boolean}
        # Returns if there is any word in the trie
        # that starts with the given prefix.
        def startsWith(self, prefix):
            current = self.root
            for letter in prefix:
                if letter not in current:
                    return False
                current = current[letter]
            return True
    
    # Now test the class
    
    test = Trie()
    test.insert('helloworld')
    test.insert('ilikeapple')
    test.insert('helloz')
    
    print test.search('hello')
    print test.startsWith('hello')
    print test.search('ilikeapple')
    

提交回复
热议问题