An example of a dictionary tree implementation method for Python data structures and algorithms
- 2020-06-15 09:43:15
- OfStack
An example of Python data structure and algorithm is presented in this paper. To share for your reference, specific as follows:
class TrieTree():
def __init__(self):
self.root = {}
def addNode(self,str):
# Every node in the tree ( Grubbing node ) , the number of words to the node, and the key that appears after the node
nowdict = self.root
for i in range(len(str)):
if str[i] not in nowdict: # Discover new combinations
nowdict[str[i]] = {'count':0,'prefix':str[:i+1]}
nowdict = nowdict[str[i]] # Transferred to the 1 A node
nowdict['count'] += 1
def countWord(self,str):
# Returns the number of times the input word appears in the tree
nowdict = self.root
for s in str:
if s not in nowdict:
return 0
nowdict = nowdict[s] # Match current node , Turn down 1 A node
# In this 1 Step by step to prove that the word exists
return nowdict['count']
if __name__=="__main__":
pass
Text = ['b','abc','abd','bcd','abcd','efg','hii','bcd']
t = TrieTree()
for str in Text:
t.addNode(str)
print t.countWord('bcd')
>>> 2
For more information about Python, please refer to Python Data Structure and Algorithm Tutorial, Python Encryption and Decryption Algorithm and Skills Summary, Python Coding skills Summary, Python Function Use Skills Summary, Python String Manipulation Skills Summary and Python Introduction and Advanced Classic Tutorial.
I hope this article has been helpful in Python programming.