Python implements a simple dictionary tree.
This example describes how to implement a simple dictionary tree in Python. We will share this with you for your reference. The details are as follows:
# Coding = utf8 "code implements the simplest dictionary tree and only supports strings consisting of lower-case letters. Based on this code, you can implement a complex dictionary tree, such as a dictionary tree with a statistical number, more characters, or deletion. "Class TrieNode (object): def _ init _ (self): # Whether to constitute a complete word self. is_word = False self. children = [None] * 26 class Trie (object): def _ init _ (self): self. root = TrieNode () def add (self, s): "" Add a string to this trie. "" p = self. root n = len (s) for I in range (n): if p. children [ord (s [I])-ord ('A')] is None: new_node = TrieNode () if I = n-1: new_node.is_word = True p. children [ord (s [I])-ord ('A')] = new_node p = new_node else: p = p. children [ord (s [I])-ord ('A')] if I = n-1: p. is_word = True return def search (self, s): "" Judge whether s is in this trie. "" p = self. root for c in s: p = p. children [ord (c)-ord ('A')] if p is None: return False if p. is_word: return True else: return Falseif _ name _ = '_ main _': trie = Trie () trie. add ('str') trie. add ('acb') trie. add ('acblde') print trie. search ('acb') print trie. search ('ac') trie. add ('ac') print trie. search ('ac ')