Python data structures and algorithms--dictionary tree

Source: Internet
Author: User

1 classTrietree ():2     def __init__(self):3Self.root = {}4     5     defAddNode (SELF,STR):6         #each node (root node) in the tree that contains the number of words to that node, and the key that appears after the node.7Nowdict =Self.root8          forIinchRange (len (str)):9             ifStr[i] not inchNowdict:#discover new ways to combineTenNowdict[str[i]] = {'Count'70A'prefix': str[:i+1]} OneNowdict = Nowdict[str[i]]#move to the next node. Anowdict['Count'] + = 1 -      -     defCountword (SELF,STR): the         #returns the number of occurrences of the input word in the tree -Nowdict =Self.root -          forSinchStr: -             ifS not inchnowdict: +                 return0 -Nowdict = Nowdict[s]#match the current node and go to the next node . +         #This step proves the existence of the word A         returnnowdict['Count'] at  -  -  -  -  - if __name__=="__main__": in     Pass -Text = ['b','ABC','Abd','BCD','ABCD','EFG','hii','BCD'] tot =Trietree () +      forStrinchText: - T.addnode (str) the     PrintT.countword ('BCD') *  $>>> 2

Reference: http://blog.csdn.net/v_july_v/article/details/6897097

Python data structures and algorithms--dictionary tree

Related Article

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.