Python Trie樹 字典樹 的實現方式

2021-10-04 12:33:34 字數 2994 閱讀 1009

今天學習到了trie樹

字典樹的詳細定義可以看

how to create a trie in python

class

trie

:def

__init__

(self)

: self._end =

'_end_'

defmake_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'

))

控制台輸出

}}

,'b':}

,'z':}

}}

class

trie

:def

__init__

(self)

: self._end =

'_end_'

defmake_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

defin_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

給定乙個單詞列表,我們將這個列表編碼成乙個索引字串 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的官方實現才是最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)

iflen

(nodes[i])==

0)

奇怪的知識又增加了哈哈哈~

今早還學習到了

set

.discard(ele)

# 可以移除集合中不存在的元素

Trie樹(字典樹)

trie樹的核心思想是用空間換時間,通過在樹中儲存字串的公共字首,來達到加速檢索的目的。例如,對於一棵儲存由英文本母組成的字串的trie樹,如下圖 trie樹在實現的時候,可以用左兒子右兄弟的表示方法,也可以在每個節點處開設乙個陣列,如上圖的方法。trie樹的主要操作是插入 查詢,也可以進行刪除。插...

字典樹 Trie樹

字典樹 trie樹 顧名思義是一種樹形結構,屬於雜湊樹的一種。應用於統計 排序 查詢單詞 統計單詞出現的頻率等。它的優點是 利用字串的公共字首來節約儲存空間,最大限度地減少無謂的字串比較,查詢效率比雜湊表高。字典樹的結構特點 根節點不代表任何字元。其他節點從當前節點回溯到根節點可以得到它代表的字串。...

字典樹 trie樹

amy 56 ann 15 emma 30 rob 27 roger 52首先存入amy,level 0表示根,不持有資料。其餘每個節點持有乙個字元 葉子節點持有資料,且持有的字元為 0 level 0 root a level 1 m level 2 y level 3 0 56 level 4新...