3
3
4
4
END = "#"
5
5
6
+
6
7
class Trie :
7
8
def __init__ (self ) -> None :
8
9
self ._trie : Dict [str , Union [Dict , bool ]] = {}
@@ -30,6 +31,7 @@ def find_word(self, prefix: str) -> Union[List[str], Tuple[str, ...]]:
30
31
31
32
def delete_word (self , word : str ) -> None :
32
33
"""Deletes a word from the trie if it exists, case insensitive."""
34
+
33
35
def _delete (node : Dict [str , Union [Dict , bool ]], word : str , depth : int ) -> bool :
34
36
if depth == len (word ):
35
37
if END in node :
@@ -41,7 +43,7 @@ def _delete(node: Dict[str, Union[Dict, bool]], word: str, depth: int) -> bool:
41
43
del node [char ]
42
44
return len (node ) == 0
43
45
return False
44
-
46
+
45
47
_delete (self ._trie , word .lower (), 0 )
46
48
47
49
def _elements (self , node : Dict [str , Union [Dict , bool ]]) -> Tuple [str , ...]:
@@ -55,6 +57,7 @@ def _elements(self, node: Dict[str, Union[Dict, bool]]) -> Tuple[str, ...]:
55
57
result .extend (sub_result )
56
58
return tuple (result )
57
59
60
+
58
61
# Example usage of the enhanced Trie class
59
62
def autocomplete_using_trie (prefix : str , trie : Trie ) -> Tuple [str , ...]:
60
63
"""
@@ -74,6 +77,7 @@ def autocomplete_using_trie(prefix: str, trie: Trie) -> Tuple[str, ...]:
74
77
suffixes = trie .find_word (prefix )
75
78
return tuple (prefix + suffix for suffix in suffixes )
76
79
80
+
77
81
def main () -> None :
78
82
trie = Trie ()
79
83
words = ("depart" , "detergent" , "daring" , "dog" , "deer" , "deal" )
@@ -83,7 +87,9 @@ def main() -> None:
83
87
trie .delete_word ("detergent" )
84
88
print (autocomplete_using_trie ("de" , trie ))
85
89
90
+
86
91
if __name__ == "__main__" :
87
92
import doctest
93
+
88
94
doctest .testmod ()
89
95
main ()
0 commit comments