Skip to content

Commit bb83ee5

Browse files
committed
Enhanced Trie implementation with improved type
hinting, docstrings, and readability. Refactored variable names, optimized node handling, and ensured consistency in return types. Updated doctests for accuracy.
1 parent b6a412e commit bb83ee5

File tree

1 file changed

+31
-28
lines changed

1 file changed

+31
-28
lines changed

strings/autocomplete_using_trie.py

+31-28
Original file line numberDiff line numberDiff line change
@@ -1,65 +1,68 @@
11
from __future__ import annotations
2+
from typing import Dict, List, Tuple, Union
23

34
END = "#"
45

5-
66
class Trie:
77
def __init__(self) -> None:
8-
self._trie: dict = {}
8+
self._trie: Dict[str, Union[Dict, bool]] = {}
99

10-
def insert_word(self, text: str) -> None:
11-
trie = self._trie
12-
for char in text:
13-
if char not in trie:
14-
trie[char] = {}
15-
trie = trie[char]
16-
trie[END] = True
10+
def insert_word(self, word: str) -> None:
11+
"""Inserts a word into the trie."""
12+
node = self._trie
13+
for char in word:
14+
if char not in node:
15+
node[char] = {}
16+
node = node[char]
17+
node[END] = True
1718

18-
def find_word(self, prefix: str) -> tuple | list:
19-
trie = self._trie
19+
def find_word(self, prefix: str) -> Union[List[str], Tuple[str]]:
20+
"""Finds all suffixes in the trie that match the given prefix."""
21+
node = self._trie
2022
for char in prefix:
21-
if char in trie:
22-
trie = trie[char]
23+
if char in node:
24+
node = node[char]
2325
else:
2426
return []
25-
return self._elements(trie)
27+
return self._elements(node)
2628

27-
def _elements(self, d: dict) -> tuple:
29+
def _elements(self, node: Dict[str, Union[Dict, bool]]) -> Tuple[str, ...]:
30+
"""Recursively collects all words from the current node."""
2831
result = []
29-
for c, v in d.items():
30-
sub_result = [" "] if c == END else [(c + s) for s in self._elements(v)]
31-
result.extend(sub_result)
32+
for char, next_node in node.items():
33+
if char == END:
34+
result.append("")
35+
else:
36+
sub_result = [char + suffix for suffix in self._elements(next_node)]
37+
result.extend(sub_result)
3238
return tuple(result)
3339

34-
3540
trie = Trie()
3641
words = ("depart", "detergent", "daring", "dog", "deer", "deal")
3742
for word in words:
3843
trie.insert_word(word)
3944

40-
41-
def autocomplete_using_trie(string: str) -> tuple:
45+
def autocomplete_using_trie(prefix: str) -> Tuple[str, ...]:
4246
"""
47+
Autocompletes the given prefix using the trie.
48+
4349
>>> trie = Trie()
4450
>>> for word in words:
4551
... trie.insert_word(word)
4652
...
4753
>>> matches = autocomplete_using_trie("de")
48-
>>> "detergent " in matches
54+
>>> "detergent" in matches
4955
True
50-
>>> "dog " in matches
56+
>>> "dog" in matches
5157
False
5258
"""
53-
suffixes = trie.find_word(string)
54-
return tuple(string + word for word in suffixes)
55-
59+
suffixes = trie.find_word(prefix)
60+
return tuple(prefix + suffix for suffix in suffixes)
5661

5762
def main() -> None:
5863
print(autocomplete_using_trie("de"))
5964

60-
6165
if __name__ == "__main__":
6266
import doctest
63-
6467
doctest.testmod()
6568
main()

0 commit comments

Comments
 (0)