Skip to content

Commit 666fe8d

Browse files
authored
Merge pull request #1 from Brahanyaa98/Brahanyaa98-patch-1
Create trie.py
2 parents 3cfcdf2 + d1e49d8 commit 666fe8d

File tree

1 file changed

+84
-0
lines changed

1 file changed

+84
-0
lines changed

trie.py

Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
2+
from typing import Tuple
3+
4+
5+
class TrieNode(object):
6+
"""
7+
Our trie node implementation. Very basic. but does the job
8+
"""
9+
10+
def __init__(self, char: str):
11+
self.char = char
12+
self.children = []
13+
# Is it the last character of the word.`
14+
self.word_finished = False
15+
# How many times this character appeared in the addition process
16+
self.counter = 1
17+
18+
19+
def add(root, word: str):
20+
"""
21+
Adding a word in the trie structure
22+
"""
23+
node = root
24+
for char in word:
25+
found_in_child = False
26+
# Search for the character in the children of the present `node`
27+
for child in node.children:
28+
if child.char == char:
29+
# We found it, increase the counter by 1 to keep track that another
30+
# word has it as well
31+
child.counter += 1
32+
# And point the node to the child that contains this char
33+
node = child
34+
found_in_child = True
35+
break
36+
# We did not find it so add a new chlid
37+
if not found_in_child:
38+
new_node = TrieNode(char)
39+
node.children.append(new_node)
40+
# And then point node to the new child
41+
node = new_node
42+
# Everything finished. Mark it as the end of a word.
43+
node.word_finished = True
44+
45+
46+
def find_prefix(root, prefix: str) -> Tuple[bool, int]:
47+
"""
48+
Check and return
49+
1. If the prefix exsists in any of the words we added so far
50+
2. If yes then how may words actually have the prefix
51+
"""
52+
node = root
53+
# If the root node has no children, then return False.
54+
# Because it means we are trying to search in an empty trie
55+
if not root.children:
56+
return False, 0
57+
for char in prefix:
58+
char_not_found = True
59+
# Search through all the children of the present `node`
60+
for child in node.children:
61+
if child.char == char:
62+
# We found the char existing in the child.
63+
char_not_found = False
64+
# Assign node as the child containing the char and break
65+
node = child
66+
break
67+
# Return False anyway when we did not find a char.
68+
if char_not_found:
69+
return False, 0
70+
# Well, we are here means we have found the prefix. Return true to indicate that
71+
# And also the counter of the last node. This indicates how many words have this
72+
# prefix
73+
return True, node.counter
74+
75+
if __name__ == "__main__":
76+
root = TrieNode('*')
77+
add(root, "hackathon")
78+
add(root, 'hack')
79+
80+
print(find_prefix(root, 'hac'))
81+
print(find_prefix(root, 'hack'))
82+
print(find_prefix(root, 'hackathon'))
83+
print(find_prefix(root, 'ha'))
84+
print(find_prefix(root, 'hammer'))

0 commit comments

Comments
 (0)