-
Notifications
You must be signed in to change notification settings - Fork 222
/
contacts.py
46 lines (37 loc) · 1.19 KB
/
contacts.py
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
#!/usr/bin/env python3
class Trie:
def __init__(self):
self.count = 1
self.children = {}
def add(self, name):
node = self
for let in name:
if let in node.children.keys():
node.children[let].count += 1
node = node.children[let]
else:
node.children[let] = Trie()
node = node.children[let]
def find(self, name):
node = self
for let in name:
if let in node.children.keys():
res = node.children[let].count
node = node.children[let]
else:
res = 0
break
return res
def print(self):
print("count = {} keys = {}".format(self.count, self.children.keys()))
for key in self.children.keys():
self.children[key].print()
if __name__ == "__main__":
t = int(input().strip())
trie = Trie()
for _ in range(t):
args = input().strip().split()
if args[0] == 'add':
trie.add(args[1])
elif args[0] == 'find':
print(trie.find(args[1]))