33
44END = "#"
55
6+
67class Trie :
78 def __init__ (self ) -> None :
89 self ._trie : Dict [str , Union [Dict , bool ]] = {}
@@ -30,6 +31,7 @@ def find_word(self, prefix: str) -> Union[List[str], Tuple[str, ...]]:
3031
3132 def delete_word (self , word : str ) -> None :
3233 """Deletes a word from the trie if it exists, case insensitive."""
34+
3335 def _delete (node : Dict [str , Union [Dict , bool ]], word : str , depth : int ) -> bool :
3436 if depth == len (word ):
3537 if END in node :
@@ -41,7 +43,7 @@ def _delete(node: Dict[str, Union[Dict, bool]], word: str, depth: int) -> bool:
4143 del node [char ]
4244 return len (node ) == 0
4345 return False
44-
46+
4547 _delete (self ._trie , word .lower (), 0 )
4648
4749 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, ...]:
5557 result .extend (sub_result )
5658 return tuple (result )
5759
60+
5861# Example usage of the enhanced Trie class
5962def autocomplete_using_trie (prefix : str , trie : Trie ) -> Tuple [str , ...]:
6063 """
@@ -74,6 +77,7 @@ def autocomplete_using_trie(prefix: str, trie: Trie) -> Tuple[str, ...]:
7477 suffixes = trie .find_word (prefix )
7578 return tuple (prefix + suffix for suffix in suffixes )
7679
80+
7781def main () -> None :
7882 trie = Trie ()
7983 words = ("depart" , "detergent" , "daring" , "dog" , "deer" , "deal" )
@@ -83,7 +87,9 @@ def main() -> None:
8387 trie .delete_word ("detergent" )
8488 print (autocomplete_using_trie ("de" , trie ))
8589
90+
8691if __name__ == "__main__" :
8792 import doctest
93+
8894 doctest .testmod ()
8995 main ()
0 commit comments