File tree Expand file tree Collapse file tree 1 file changed +62
-0
lines changed Expand file tree Collapse file tree 1 file changed +62
-0
lines changed Original file line number Diff line number Diff line change 1+ from typing import Dict , List
2+
3+
4+ class Dictionary :
5+
6+ def __init__ (self ):
7+ self .node = {}
8+
9+ def add_word (self , word : str ) -> None :
10+ node = self .node
11+ for ltr in word :
12+ if ltr not in node :
13+ node [ltr ] = {}
14+ node = node [ltr ]
15+ node ["is_word" ] = True
16+
17+ def word_exists (self , word : str ) -> bool :
18+ node = self .node
19+ for ltr in word :
20+ if ltr not in node :
21+ return False
22+ node = node [ltr ]
23+ return "is_word" in node
24+
25+ def list_words_from_node (self , node : Dict , spelling : str ) -> None :
26+ if "is_word" in node :
27+ self .words_list .append (spelling )
28+ return
29+ for ltr in node :
30+ self .list_words_from_node (node [ltr ], spelling + ltr )
31+
32+ def print_all_words_in_dictionary (self ) -> List [str ]:
33+ node = self .node
34+ self .words_list = []
35+ self .list_words_from_node (node , "" )
36+ return self .words_list
37+
38+ def suggest_words_starting_with (self , prefix : str ) -> List [str ]:
39+ node = self .node
40+ for ltr in prefix :
41+ if ltr not in node :
42+ return False
43+ node = node [ltr ]
44+ self .words_list = []
45+ self .list_words_from_node (node , prefix )
46+ return self .words_list
47+
48+
49+
50+
51+ # Your Dictionary object will be instantiated and called as such:
52+ obj = Dictionary ()
53+ obj .add_word ("word" )
54+ obj .add_word ("woke" )
55+ obj .add_word ("happy" )
56+
57+ param_2 = obj .word_exists ("word" )
58+ param_3 = obj .suggest_words_starting_with ("wo" )
59+
60+ print (param_2 )
61+ print (param_3 )
62+ print (obj .print_all_words_in_dictionary ())
You can’t perform that action at this time.
0 commit comments