Elegant python and elegant python

Source: Internet
Author: User

Elegant python and elegant python

Trie, also known as the Prefix Tree or dictionary tree, uses the common prefix of the string to save storage space.

  • Definition
    Each word in the Trie tree is stored using the character by character method. words with the same prefix share the prefix node.

    As you can see, each path is a word. The tree above contains the words to/tea/ted/ten/inn.

    • Nature
      • (1) The root node does not contain characters. Each node except the root node only contains one character.
      • (2) From the root node to a node, the character passing through the path is connected to the string corresponding to the node.
      • (3) the strings of all subnodes of each node are different.
  • Application
    • Word Frequency Statistics
      Space saving compared with direct use of hash
    • Search Prompt
      When you enter a prefix, the system prompts the words that can be entered.
    • Auxiliary Structure
      Auxiliary structures such as suffix tree and AC automatic mechanism
  • Implementation
    Although python does not have pointers, nested Dictionaries can be used to implement tree structures. For non-ascii words, unicode encoding is used for insertion and search.


# Coding = utf-8class Trie: root = {} END = '/' def add (self, word): # traverse words from the root node, char by char, new if not present, add a word ending sign node = self. root for c in word: node = node. setdefault (c, {}) node [self. END] = None def find (self, word): node = self. root for c in word: if c not in node: return False node = node [c] return self. END in node

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.