Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit 313a043

Browse files
ArchanaPrabhucclauss
authored andcommitted
Create autocomplete_using_trie.py (TheAlgorithms#1406)
* Create autocomplete_using_trie.py The program aims to design a trie implementation for autocomplete which is easy to understand and ready to run. * Removed unused import * Updated the list value * Update autocomplete_using_trie.py * Run the code through Black and add doctest
1 parent 38d7e70 commit 313a043

File tree

1 file changed

+64
-0
lines changed

1 file changed

+64
-0
lines changed

other/autocomplete_using_trie.py

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
END = "#"
2+
3+
4+
class Trie:
5+
def __init__(self):
6+
self._trie = {}
7+
8+
def insert_word(self, text):
9+
trie = self._trie
10+
for char in text:
11+
if char not in trie:
12+
trie[char] = {}
13+
trie = trie[char]
14+
trie[END] = True
15+
16+
def find_word(self, prefix):
17+
trie = self._trie
18+
for char in prefix:
19+
if char in trie:
20+
trie = trie[char]
21+
else:
22+
return []
23+
return self._elements(trie)
24+
25+
def _elements(self, d):
26+
result = []
27+
for c, v in d.items():
28+
if c == END:
29+
subresult = [" "]
30+
else:
31+
subresult = [c + s for s in self._elements(v)]
32+
result.extend(subresult)
33+
return tuple(result)
34+
35+
36+
trie = Trie()
37+
words = ("depart", "detergent", "daring", "dog", "deer", "deal")
38+
for word in words:
39+
trie.insert_word(word)
40+
41+
42+
def autocomplete_using_trie(s):
43+
"""
44+
>>> trie = Trie()
45+
>>> for word in words:
46+
... trie.insert_word(word)
47+
...
48+
>>> matches = autocomplete_using_trie("de")
49+
50+
"detergent " in matches
51+
True
52+
"dog " in matches
53+
False
54+
"""
55+
suffixes = trie.find_word(s)
56+
return tuple(s + w for w in suffixes)
57+
58+
59+
def main():
60+
print(autocomplete_using_trie("de"))
61+
62+
63+
if __name__ == "__main__":
64+
main()

0 commit comments

Comments
 (0)