forked from TheAlgorithms/Python
- Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathautocomplete_using_trie.py
65 lines (50 loc) · 1.45 KB
/
autocomplete_using_trie.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
from __future__ importannotations
END="#"
classTrie:
def__init__(self) ->None:
self._trie: dict= {}
definsert_word(self, text: str) ->None:
trie=self._trie
forcharintext:
ifcharnotintrie:
trie[char] = {}
trie=trie[char]
trie[END] =True
deffind_word(self, prefix: str) ->tuple|list:
trie=self._trie
forcharinprefix:
ifcharintrie:
trie=trie[char]
else:
return []
returnself._elements(trie)
def_elements(self, d: dict) ->tuple:
result= []
forc, vind.items():
sub_result= [" "] ifc==ENDelse [(c+s) forsinself._elements(v)]
result.extend(sub_result)
returntuple(result)
trie=Trie()
words= ("depart", "detergent", "daring", "dog", "deer", "deal")
forwordinwords:
trie.insert_word(word)
defautocomplete_using_trie(string: str) ->tuple:
"""
>>> trie = Trie()
>>> for word in words:
... trie.insert_word(word)
...
>>> matches = autocomplete_using_trie("de")
>>> "detergent " in matches
True
>>> "dog " in matches
False
"""
suffixes=trie.find_word(string)
returntuple(string+wordforwordinsuffixes)
defmain() ->None:
print(autocomplete_using_trie("de"))
if__name__=="__main__":
importdoctest
doctest.testmod()
main()