-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathontology.py
More file actions
40 lines (31 loc) · 1.02 KB
/
ontology.py
File metadata and controls
40 lines (31 loc) · 1.02 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
from collections import namedtuple
def ontology(treeRepr, questions, queries):
Node = namedtuple('Node', ['name', 'children', 'questions'])
root_name, *descendants = treeRepr.split(' ')
root = Node(root_name, [], [])
index = {root_name: root}
trees = [root]
prior = []
for k in descendants:
if k == '(':
prior.append(trees)
trees = trees[-1].children
elif k == ')':
trees = prior.pop()
else:
child = Node(k, [], [])
trees.append(child)
index[k] = child
for q in questions:
k, v = q.split(': ')
index[k].questions.append(v)
def search(tree, words):
temp = sum(q.startswith(words) for q in tree.questions)
temp += sum(search(t, words) for t in tree.children)
return temp
ans = []
for q in queries:
topic, *words = q.split(' ')
words = ' '.join(words)
ans.append(search(index[topic], words))
return ans