How to create a trie in Python

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

    Using defaultdict and reduce function.

    Create Trie

    from functools import reduce
    from collections import defaultdict
    T = lambda : defaultdict(T)
    trie = T()
    reduce(dict.__getitem__,'how',trie)['isEnd'] = True
    

    Trie :

    defaultdict(()>,
                {'h': defaultdict(()>,
                             {'o': defaultdict(()>,
                                          {'w': defaultdict(()>,
                                                       {'isEnd': True})})})})
    

    Search In Trie :

    curr = trie
    for w in 'how':
        if w in curr:
            curr = curr[w]
        else:
            print("Not Found")
            break
    if curr['isEnd']:
        print('Found')
    

提交回复
热议问题