Skip to content

Commit 9a52167

Browse files
committed
Finished Simple Trie implementation and added test functions
* Finished function to insert a word into Trie * Finished function to find a word in the Trie * Added Test functions with Assertions
1 parent 03b7600 commit 9a52167

File tree

1 file changed

+61
-5
lines changed

1 file changed

+61
-5
lines changed

Diff for: data_structures/Trie/Trie.py

+61-5
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,77 @@
1-
'''
1+
"""
22
A Trie/Prefix Tree is a kind of search tree used to provide quick lookup
33
of words/patterns in a set of words. A basic Trie however has O(n^2) space complexity
44
making it impractical in practice. It however provides O(max(search_string, length of longest word)) lookup
55
time making it an optimal approach when space is not an issue.
6-
'''
6+
7+
This implementation assumes the character $ is not in any of the words. This character is used in the implementation
8+
to mark the end of a word.
9+
"""
710

811

912
class TrieNode:
1013
def __init__(self):
11-
self.nodes = dict() # Mapping from char to TrieNode
14+
self.nodes = dict() # Mapping from char to TrieNode
1215

1316
def insert_many(self, words: [str]):
17+
"""
18+
Inserts a list of words into the Trie
19+
:param words: list of string words
20+
:return: None
21+
"""
1422
for word in words:
1523
self.insert(word)
1624

1725
def insert(self, word: str):
18-
pass
26+
"""
27+
Inserts a word into the Trie
28+
:param word: word to be inserted
29+
:return: None
30+
"""
31+
word += '$'
32+
curr = self
33+
for char in word:
34+
if char not in curr.nodes:
35+
curr.nodes[char] = TrieNode()
36+
curr = curr.nodes[char]
1937

2038
def find(self, word: str) -> bool:
21-
pass
39+
"""
40+
Tries to find word in a Trie
41+
:param word: word to look for
42+
:return: Returns True if word is found, False otherwise
43+
"""
44+
word += '$'
45+
curr = self
46+
for char in word:
47+
if char not in curr.nodes:
48+
return False
49+
curr = curr.nodes[char]
50+
return True
51+
52+
53+
def print_words(node: TrieNode, word: str):
54+
"""
55+
Prints all the words in a Trie
56+
:param node: root node of Trie
57+
:param word: Word variable should be empty at start
58+
:return: None
59+
"""
60+
if '$' in node.nodes:
61+
print(word, end=' ')
62+
63+
for key, value in node.nodes.items():
64+
print_words(value, word + key)
65+
66+
67+
def test():
68+
words = ['banana', 'bananas', 'bandana', 'band', 'apple', 'all', 'beast']
69+
root = TrieNode()
70+
root.insert_many(words)
71+
# print_words(root, '')
72+
assert root.find('banana')
73+
assert not root.find('bandanas')
74+
assert not root.find('apps')
75+
assert root.find('apple')
76+
77+
# test()

0 commit comments

Comments
 (0)