本文實例講述了Python數據結構與算法之字典樹實現方法。分享給大家供大家參考,具體如下:
class TrieTree():  def __init__(self):    self.root = {}  def addNode(self,str):    # 樹中每個結點(除根節點),包含到該結點的單詞數,以及該結點后面出現字母的鍵    nowdict = self.root    for i in range(len(str)):      if str[i] not in nowdict:  # 發現新的組合方式        nowdict[str[i]] = {'count':0,'prefix':str[:i+1]}      nowdict = nowdict[str[i]]  # 轉移到下一個結點    nowdict['count'] += 1  def countWord(self,str):    # 返回輸入單詞在樹中出現的次數    nowdict = self.root    for s in str:      if s not in nowdict:        return 0      nowdict = nowdict[s]  # 匹配當前結點,轉下一個結點    # 到了這一步證明單詞存在    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更多關于Python相關內容感興趣的讀者可查看本站專題:《Python數據結構與算法教程》、《Python加密解密算法與技巧總結》、《Python編碼操作技巧總結》、《Python函數使用技巧總結》、《Python字符串操作技巧匯總》及《Python入門與進階經典教程》
希望本文所述對大家Python程序設計有所幫助。
新聞熱點
疑難解答