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