-
Notifications
You must be signed in to change notification settings - Fork 25
/
tree.py
60 lines (52 loc) · 1.8 KB
/
tree.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
import copy
from collections import defaultdict
# Create a hierarchical structure
# =========================================================
def make(): return defaultdict(make)
def dicts(t): return {k: dicts(t[k]) for k in t}
# Add labels to a hierarchical structure
# =========================================================
def add(t, path):
for node in path:
t = t[node]
# Search parent labels
# =========================================================
def search_parent(tree,child,layer=1,prev_parent='root'):
for k,v in list(tree.items()):
if(k == child):
return prev_parent
else:
if len(v) >= 1:
layer += 1
found = search_parent(v, child, layer,k)
if found:
return found
layer -=1
else:
continue
# Search child labels
# =========================================================
def search_child(tree,node,layer=1):
if (node == "root" or node =="ROOT" or node == "Root"):
return list(tree.keys())
for k,v in list(tree.items()):
if(k == node):
return list(v.keys())
else:
if len(v) >= 1:
layer += 1
found = search_child(v, node, layer)
if found:
return found
layer -=1
else:
continue
# Search path from the root of the specified label
# =========================================================
def search_path(tree, node):
start_node = copy.deepcopy(node)
path = [start_node]
while (node != "root"):
node = search_parent(tree, node)
path.append(node)
return path