Trie樹的Python實現方式

今天學習到了Trie樹
字典樹的詳細定義可以看

Stackoverflow上的簡潔實踐

How to create a trie in Python

class Trie:
    def __init__(self):
       self._end = '_end_'

    def make_trie(self,*words):
        root = dict()
        for word in words:
            current_dict = root
            for letter in word:
                current_dict = current_dict.setdefault(letter,{})
            current_dict[self._end] = self._end
        return root

if __name__ == '__main__':
    trie = Trie()
    print(trie.make_trie('foo', 'bar', 'baz', 'barz'))

控制檯輸出

{'f': {'o': {'o': {'_end_': '_end_'}}}, 
'b': {'a': {'r': {'_end_': '_end_', 'z': {'_end_': '_end_'}}, 'z': {'_end_': '_end_'}}}}

在trie樹中查找單詞

class Trie:
    def __init__(self):
       self._end = '_end_'

    def make_trie(self,*words):
        root = dict()
        for word in words:
            current_dict = root
            for letter in word:
                current_dict = current_dict.setdefault(letter,{})
            current_dict[self._end] = self._end
        return root

    def in_trie(self,trie,word):
        current_dict = trie
        for letter in word:
            if letter not in current_dict:
                return False
            current_dict = current_dict[letter]
        return self._end in current_dict

if __name__ == '__main__':
    trie = Trie()
    print(trie.make_trie('foo', 'bar', 'baz', 'barz'))
    print(trie.in_trie(trie.make_trie('foo', 'bar', 'baz', 'barz'),'bar'))
    # output: True

單詞的壓縮編碼(leetcode)

給定一個單詞列表,我們將這個列表編碼成一個索引字符串 S 與一個索引列表 A。

例如,如果這個列表是 [“time”, “me”, “bell”],我們就可以將其表示爲 S = “time#bell#” 和
indexes = [0, 2, 5]。

對於每一個索引,我們可以通過從字符串 S 中索引的位置開始讀取字符串,直到 “#” 結束,來恢復我們之前的單詞列表。

那麼成功對給定單詞列表進行編碼的最小字符串長度是多少呢?

示例:

輸入: words = [“time”, “me”, “bell”] 輸出: 10 說明: S = “time#bell#” ,
indexes = [0, 2, 5] 。

來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/short-encoding-of-words
著作權歸領釦網絡所有。商業轉載請聯繫官方授權,非商業轉載請註明出處。

我覺得leetcode的官方實現纔是最6的,pythonic極致

class Solution:
    def minimumLengthEncoding(self, words: List[str]) -> int:
        words = list(set(words)) #去重
        # Trie是帶有已創建節點的嵌套字典
        # 當其中缺少節點時會創建節點
        Trie = lambda: collections.defaultdict(Trie)
        trie = Trie()

        #reduce(..., S, trie) is trie[S[0]][S[1]][S[2]][...][S[S.length - 1]],將單詞反序插入
        nodes = [reduce(dict.__getitem__, word[::-1], trie)
                 for word in words]

        #如果節點沒有鄰居節點,則添加該單詞
        return sum(len(word) + 1
                   for i, word in enumerate(words)
                   if len(nodes[i]) == 0)

作者:LeetCode-Solution
鏈接:https://leetcode-cn.com/problems/short-encoding-of-words/solution/dan-ci-de-ya-suo-bian-ma-by-leetcode-solution/
來源:力扣(LeetCode)
著作權歸作者所有。商業轉載請聯繫作者獲得授權,非商業轉載請註明出處。

奇怪的知識又增加了哈哈哈~
今早還學習到了

set.discard(ele)# 可以移除集合中不存在的元素
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章