How to create a trie in Python

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

    This version is using recursion

    import pprint
    from collections import deque
    
    pp = pprint.PrettyPrinter(indent=4)
    
    inp = raw_input("Enter a sentence to show as trie\n")
    words = inp.split(" ")
    trie = {}
    
    
    def trie_recursion(trie_ds, word):
        try:
            letter = word.popleft()
            out = trie_recursion(trie_ds.get(letter, {}), word)
        except IndexError:
            # End of the word
            return {}
    
        # Dont update if letter already present
        if not trie_ds.has_key(letter):
            trie_ds[letter] = out
    
        return trie_ds
    
    for word in words:
        # Go through each word
        trie = trie_recursion(trie, deque(word))
    
    pprint.pprint(trie)
    

    Output:

    Coool

提交回复
热议问题