-
Notifications
You must be signed in to change notification settings - Fork 74
/
trie.py
37 lines (31 loc) · 1.05 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
# Uses python3
import sys
# Return the trie built from patterns
# in the form of a dictionary of dictionaries,
# e.g. {0:{'A':1,'T':2},1:{'C':3}}
# where the key of the external dictionary is
# the node ID (integer), and the internal dictionary
# contains all the trie edges outgoing from the corresponding
# node, and the keys are the letters on those edges, and the
# values are the node IDs to which these edges lead.
def build_trie(patterns):
tree = dict()
tree[0] = {}
index = 1
for pattern in patterns:
current = tree[0]
for letter in pattern:
if letter in current.keys():
current = tree[current[letter]]
else:
current[letter] = index
tree[index] = {}
current = tree[index]
index = index + 1
return tree
if __name__ == '__main__':
patterns = sys.stdin.read().split()[1:]
tree = build_trie(patterns)
for node in tree:
for c in tree[node]:
print("{}->{}:{}".format(node, tree[node][c], c))