-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontacts.py
More file actions
95 lines (68 loc) · 1.86 KB
/
Copy pathcontacts.py
File metadata and controls
95 lines (68 loc) · 1.86 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
85
86
87
88
89
90
91
92
93
94
95
# https://www.hackerrank.com/challenges/contacts/problem
# Trie Data Structure
#!/bin/python3
import math
import os
import random
import re
import sys
#
# Complete the 'contacts' function below.
#
# The function is expected to return an INTEGER_ARRAY.
# The function accepts 2D_STRING_ARRAY queries as parameter.
#
class Node:
def __init__(self):
self.children = {}
self.end_of_word = False
self.count = 0
class Trie(object):
def __init__(self):
self.root = Node()
def insert(self, word):
curr = self.root
for c in word:
child = curr.children.get(c, None)
if child is None:
child = Node()
curr.children[c] = child
child.count += 1
curr = child
curr.end_of_word = True
def _get_count_results(self, term):
curr = self.root
for c in term:
curr = curr.children.get(c)
return curr.count
def search(self, term):
curr = self.root
for c in term:
child = curr.children.get(c, None)
if child is None:
return 0
curr = child
count = self._get_count_results(term)
return count
def contacts(queries):
trie = Trie()
results = []
for query in queries:
action = query[0]
term = query[1]
if action == 'add':
trie.insert(term)
else:
result = trie.search(term)
results.append(result)
return results
if __name__ == '__main__':
fptr = open('file.txt', 'w')
queries_rows = int(input().strip())
queries = []
for _ in range(queries_rows):
queries.append(input().rstrip().split())
result = contacts(queries)
fptr.write('\n'.join(map(str, result)))
fptr.write('\n')
fptr.close()