Skip to content

Commit 6b60aee

Browse files
committed
Add trie
1 parent 0786a98 commit 6b60aee

File tree

1 file changed

+104
-0
lines changed

1 file changed

+104
-0
lines changed

Data_Structure/src/Trees/trie.py

Lines changed: 104 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,104 @@
1+
"""Trie implementation in Python"""
2+
3+
4+
class _TrieNode:
5+
def __init__(self):
6+
self.words = 0
7+
self.children = {}
8+
9+
def __len__(self):
10+
return self.words + sum(len(c) for c in self.children.values())
11+
12+
def add(self, s):
13+
if not s:
14+
self.words += 1
15+
return
16+
if s[0] not in self.children:
17+
self.children[s[0]] = _TrieNode()
18+
self.children[s[0]].add(s[1:])
19+
20+
def remove(self, s):
21+
if not s:
22+
if not self.words:
23+
raise ValueError
24+
self.words -= 1
25+
return
26+
if s[0] not in self.children:
27+
raise ValueError
28+
self.children[s[0]].remove(s[1:])
29+
30+
def count(self, s):
31+
if not s:
32+
return self.words
33+
if s[0] not in self.children:
34+
return 0
35+
return self.children[s[0]].count(s[1:])
36+
37+
def get_words(self):
38+
words = [""] * self.words
39+
for c in self.children:
40+
for w in self.children[c].get_words():
41+
words.append(c + w)
42+
return words
43+
44+
45+
class Trie:
46+
def __init__(self, *words):
47+
self.children = {}
48+
for w in words:
49+
self.add(w)
50+
51+
def __contains__(self, item):
52+
return bool(self.count(item))
53+
54+
def __len__(self):
55+
return sum(len(c) for c in self.children.values())
56+
57+
def __bool__(self):
58+
return bool(len(self))
59+
60+
def __repr__(self):
61+
return "{}({})".format(self.__class__.__name__, ", ".join([repr(w) for w in self.get_words()]))
62+
63+
def add(self, s):
64+
if not s:
65+
raise ValueError("Empty strings disallowed")
66+
if s[0] not in self.children:
67+
self.children[s[0]] = _TrieNode()
68+
self.children[s[0]].add(s[1:])
69+
70+
def remove(self, s):
71+
if not s:
72+
raise ValueError("Empty strings disallowed")
73+
try:
74+
if s[0] not in self.children:
75+
raise ValueError
76+
self.children[s[0]].remove(s[1:])
77+
except ValueError:
78+
raise ValueError("{} not in trie".format(repr(s))) from None
79+
80+
def count(self, s):
81+
if s[0] not in self.children:
82+
return 0
83+
return self.children[s[0]].count(s[1:])
84+
85+
def get_words(self):
86+
words = []
87+
for c in self.children:
88+
for w in self.children[c].get_words():
89+
words.append(c + w)
90+
return words
91+
92+
93+
def main():
94+
trie = Trie("dog", "dog", "cat", "tiger")
95+
trie.add("bird")
96+
trie.remove("bird")
97+
print("repr(trie):", trie)
98+
print("len(trie):", len(trie))
99+
print("trie.count('dog'):", trie.count("dog"))
100+
print("'bird' in trie:", "bird" in trie)
101+
102+
103+
if __name__ == "__main__":
104+
main()

0 commit comments

Comments
 (0)