-
Notifications
You must be signed in to change notification settings - Fork 0
/
autoComplete.py
52 lines (37 loc) · 1.08 KB
/
autoComplete.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
__author__ = 'kathan'
class Node():
def __init__(self, prefix):
self.prefix = prefix
self.children = {}
self.is_word = False
trie = Node("")
def insertWords(word):
global trie
current = trie
for index, char in enumerate(word):
if char not in current.children:
current.children[char] = Node(word[0:index + 1])
current = current.children[char]
current.is_word = True
def autoComplete(dictionary):
for word in dictionary:
insertWords(word)
def findAllWords(node, results):
if node.is_word:
results.append(node.prefix)
for char in node.children:
findAllWords(node.children[char], results)
def getWordsForPrefix(prefix):
results = []
global trie
current = trie
for char in prefix:
if char in current.children:
current = current.children[char]
else:
return results
findAllWords(current, results)
return results
autoComplete(["abc", "acd", "bcd", "def", "a", "aba"])
print getWordsForPrefix('ab')
print getWordsForPrefix('b')