The examples in this article describe how Python implements a simple dictionary tree. Share to everyone for your reference, as follows:
#coding =utf8 "" "Code implements the simplest dictionary tree and supports only lowercase letters of a string. By extending this code, you can implement a more complex dictionary tree, such as a dictionary tree with statistics or support for more characters, or a delete operation. "" "Class Trienode (object): Def __init__ (self): # Whether it constitutes a finished word Self.is_word = False Self.children = [None] * 26CLA SS 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 = Tri Enode () 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 was 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 ')
For more information about Python, see the topic: a summary of Python dictionary operations skills, a summary of Python regular expression usage, a tutorial on Python data Structures and algorithms, a summary of Python socket programming tips, Python function Usage Tips Summary, python string manipulation tips Summary, Python Introductory and Advanced classic tutorials, and Python file and directory Operations Tips Summary
I hope this article is helpful for Python program design.