File tree Expand file tree Collapse file tree 1 file changed +50
-0
lines changed Expand file tree Collapse file tree 1 file changed +50
-0
lines changed Original file line number Diff line number Diff line change
1
+ import pickle
2
+
3
+ from collections import deque
4
+
5
+
6
+ def get_subtree (word , trie ):
7
+ parent = trie
8
+ for char in word :
9
+ try :
10
+ parent = parent [char ]
11
+ except KeyError :
12
+ parent = {}
13
+ return parent
14
+
15
+
16
+ def isword (word , trie ):
17
+ try :
18
+ return get_subtree (word , trie )['isword' ]
19
+ except KeyError :
20
+ return False
21
+
22
+
23
+ def get_words (substr , trie ):
24
+ words = []
25
+ if isword (substr , trie ):
26
+ words .append (substr )
27
+
28
+ root = get_subtree (substr , trie )
29
+ queue = deque ([[substr , c ] for c in root if c != 'isword' ])
30
+ while queue :
31
+ path , char = queue .popleft ()
32
+ word = path + char
33
+ if isword (word , trie ):
34
+ words .append (word )
35
+ for child in get_subtree (word , trie ):
36
+ if child == 'isword' :
37
+ continue
38
+ queue .append ([word , child ])
39
+
40
+ return words
41
+
42
+
43
+ def main ():
44
+ substring = 'pyt'
45
+ trie = pickle .load (open ('tests/words_trie.pkl' , 'rb' ))
46
+ print (get_words (substring , trie ))
47
+
48
+
49
+ if __name__ == '__main__' :
50
+ main ()
You can’t perform that action at this time.
0 commit comments