-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathtrie.py
More file actions
67 lines (59 loc) · 1.83 KB
/
trie.py
File metadata and controls
67 lines (59 loc) · 1.83 KB
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
endOfWord = "$"
def generateTrieFromWordsArray(words):
root = {}
for word in words:
currentDict = root
for letter in word:
currentDict = currentDict.setdefault(letter, {})
currentDict[endOfWord] = endOfWord
return root
def generateTrieFromWordsArrayAndCountRepititions(words):
root = {}
for word in words:
currentDict = root
for letter in word:
currentDict = currentDict.setdefault(letter, {})
if endOfWord in currentDict:
currentDict[endOfWord] = currentDict[endOfWord] + 1
else:
currentDict[endOfWord] = 1
return root
def isWordPresentInTrie(trie, word):
currentDict = trie
for letter in word:
if letter in currentDict:
currentDict = currentDict[letter]
else:
return False
if endOfWord in currentDict:
return True
else:
return False
def offerPossibleCompletionsToStringInTrie(trie, string):
currentDict = trie
# step down to provided beginning of words
for letter in string:
if letter in currentDict:
currentDict = currentDict[letter]
else:
return "Trie does not offer any completions to %s" % (string)
# now current dict is at the level which would offer completions.
printCompletionsFromNode(currentDict, string)
def printCompletionsFromNode(trie, string):
currentDict = trie
word = string
# iterate over all children of the current letter node
for letter in currentDict:
# if the word is completed, print it
if letter == "$":
print(word)
else:
word = string + letter
# function calls itself to handle all possible completions
printCompletionsFromNode(currentDict[letter], word)
arrayOfWords = ['hello', 'hey', 'what', 'when', 'why']
wordsTrie = generateTrieFromWordsArray(arrayOfWords)
# print wordsTrie['h']['e']
# print isWordPresentInTrie(wordsTrie, 'hello')
# print isWordPresentInTrie(wordsTrie, 'hellow')
print offerPossibleCompletionsToStringInTrie(wordsTrie, 'w')