-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontacts.py
More file actions
63 lines (44 loc) · 1.35 KB
/
contacts.py
File metadata and controls
63 lines (44 loc) · 1.35 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
class Node:
def __init__(self):
self.children = {}
self.is_complete_word = False
self.children_count = 0
def __str__(self):
result = str(self.children) + ' ' + str(self.is_complete_word)
for child in self.children:
result += str(self.children[child])
return result
def add_contact(contacts, name):
current = contacts
for c in name:
if c in current.children:
current = current.children[c]
else:
current.children[c] = Node()
current = current.children[c]
current.children_count += 1
current.is_complete_word = True
return current
def count_children(parent):
result = int(parent.is_complete_word)
if not parent.children:
return result
for child in parent.children:
result += count_children(parent.children[child])
return result
def find_contact(contacts, name):
current = contacts
for c in name:
if c in current.children:
current = current.children[c]
else:
return 0
return current.children_count
contacts = Node()
n = int(input().strip())
for a0 in range(n):
op, contact = input().strip().split(' ')
if op == 'add':
add_contact(contacts, contact)
elif op == 'find':
print(find_contact(contacts, contact))