Python's approach to implementing a simple dictionary tree

Source: Internet
Author: User
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.

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.