-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtrie.py
91 lines (63 loc) · 1.89 KB
/
trie.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
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
#!/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.size = 0
def __repr__(self):
return repr(self.children)
def __get_char_ascii(self, char):
return ord(char)
def add(self, word):
self._add(word, 0)
def _add(self, word, index):
self.size += 1
if len(word) == index:
return
letter = word[index]
ascii_value = self.__get_char_ascii(letter)
child = self.children.get(ascii_value)
if child is None:
child = Node()
self.children[ascii_value] = child
child._add(word, index + 1)
def find(self, word):
return self._find(word, 0)
def _find(self, word, index):
if len(word) == index:
return self.size
letter = word[index]
ascii_value = self.__get_char_ascii(letter)
child = self.children.get(ascii_value)
if child is None:
return 0
return child._find(word, index+1)
def contacts(queries):
node = Node()
result = []
for query in queries:
if query[0] == 'add':
node.add(query[1])
else:
result.append(node.find(query[1]))
return result
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], '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()