-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathtrie.py
More file actions
84 lines (59 loc) · 1.74 KB
/
trie.py
File metadata and controls
84 lines (59 loc) · 1.74 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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
# Inspired by blog:
# https://towardsdatascience.com/implementing-a-trie-data-structure-in-python-in-less-than-100-lines-of-code-a877ea23c1a1
class TrieNode:
def __init__(self, ch):
self.ch = ch
self.children = []
self.word_finished = False
self.counter = 1
def add(root, word):
node = root
for c in word:
ch_found = False
for child in node.children:
if child.ch == c:
child.counter += 1
node = child
ch_found = True
break
if not ch_found:
child = TrieNode(c)
node.children.append(child)
node = child
node.word_finished = True
def find_prefix(root, prefix):
node = root
for ch in prefix:
ch_found = False
for child in node.children:
if child.ch == ch:
ch_found = True
break
if not ch_found:
return False, 0
node = child
return True, node.counter
def word_exists(root, word):
node = root
for c in word:
ch_found = False
for child in node.children:
if child.ch == c:
ch_found = True
node = child
break
if not ch_found:
return False
return child.word_finished
if __name__ == '__main__':
root = TrieNode('*')
add(root, "hackathon")
add(root, 'hack')
print(find_prefix(root, 'hac'))
print(find_prefix(root, 'hack'))
print(find_prefix(root, 'hackathon'))
print(find_prefix(root, 'ha'))
print(find_prefix(root, 'hammer'))
print(word_exists(root, 'hammer'))
print(word_exists(root, 'hackathon'))
print(word_exists(root, 'hack'))