Python implements a simple dictionary tree.

Source: Internet
Author: User

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 ')

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.