-
Notifications
You must be signed in to change notification settings - Fork 223
/
Copy pathno-prefix-set.py
81 lines (67 loc) · 2.3 KB
/
no-prefix-set.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
#!/usr/bin/env python3
class Trie:
def __init__(self):
self.count = 1
self.word = 0
self.children = {}
def add(self, name):
if self.is_good(name):
node = self
for ind, let in enumerate(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]
if ind == len(name)-1:
node.word = 1
else:
return False
return True
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 = {} word = {} keys = {}".format(self.count, self.word, self.children.keys()))
for key in self.children.keys():
self.children[key].print()
def is_good(self, word):
node = self
w_len = len(word)
#if w_len == 1 and word in node.children.keys():
# return False
for ind, let in enumerate(word):
child = node.children.get(let)
if not child:
return True
node = child
#print("let = {} ind = {} w_len-1 = {} node.word = {} node.children = {}".format(let, ind, w_len-1, node.word, node.children))
if ind == w_len-1 and len(node.children.keys()) > 0:
#print("word is shorter")
return False
if ind <= w_len-1 and node.word == 1:
#print("word is longer")
return False
return True
if __name__ == "__main__":
t = int(input().strip())
trie = Trie()
passed = 1
for _ in range(t):
word = input().strip()
retc = trie.add(word)
if not retc:
print("BAD SET")
print(word)
passed = 0
break
if passed:
print("GOOD SET")