-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtrie.py
82 lines (74 loc) · 2.45 KB
/
trie.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
class TrieNode:
def __init__(self, c):
self.char = c
self.children = []
self.isCompleteWord = False
class Trie:
def __init__(self):
self.root = TrieNode("")
self.root.isCompleteWord = True
def add(self, word):
n = self.root
for c in word:
for child in n.children:
if child.char == c:
n = child
break
else:
child = TrieNode(c)
n.children.append(child)
n = child
n.isCompleteWord = True
def search(self, word):
n = self.root
for c in word:
for child in n.children:
if child.char == c:
n = child
break
else:
return False
return n.isCompleteWord
def getWords(self, prefix):
"""
Returns list of all words in trie starting with prefix
"""
def dfs(node, word):
rlist = []
word += node.char
if node.isCompleteWord:
rlist.append(word)
for child in node.children:
rlist.extend(dfs(child, word))
return rlist
n = self.root
# Look for prefix in tree
for c in prefix:
for child in n.children:
if child.char == c:
n = child
break
else:
return []
# n is now node containing last character of prefix
return dfs(n, prefix[:-1])
def getValidWords(self, charstring):
"""
Returns list of all words in trie containing *only* letters in
charstring. Letters can occur 0 or more times. All words must
contains charstring[0] (key).
"""
def dfs(node, word, includesKey, charstring, wordlist=[]):
if node.char not in charstring:
# Invalid character, so stop building the word
return
word += node.char
includesKey = includesKey or node.char == charstring[0]
if includesKey and node.isCompleteWord:
# completed word includes the key
wordlist.append(word)
# print(word)
for child in node.children:
dfs(child, word, includesKey, charstring, wordlist)
return wordlist
return dfs(self.root, "", False, charstring)