How to create a trie in Python

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

    from collections import defaultdict
    

    Define Trie:

    _trie = lambda: defaultdict(_trie)
    

    Create Trie:

    trie = _trie()
    for s in ["cat", "bat", "rat", "cam"]:
        curr = trie
        for c in s:
            curr = curr[c]
        curr.setdefault("_end")
    

    Lookup:

    def word_exist(trie, word):
        curr = trie
        for w in word:
            if w not in curr:
                return False
            curr = curr[w]
        return '_end' in curr
    

    Test:

    print(word_exist(trie, 'cam'))
    

提交回复
热议问题