-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmisc.py
74 lines (54 loc) · 1.49 KB
/
misc.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
import joblib
def savez(obj, filename, protocol=0):
"""Saves a compressed object to disk
"""
joblib.dump(obj, filename, compress=True)
def loadz(filename):
"""Loads a compressed object from disk
"""
return joblib.load(filename)
def dfs_topsort(graph, root=None):
""" Perform topological sort using a modified depth-first search
Parameters
----------
graph: dict
A directed graph
root: str, int or None
We perform topological sort for a subgraph of the given node.
If `root` is None, the entire graph is considered.
Return
------
L: list
a sorted list of nodes in the input graph
"""
L = []
color = {u: "white" for u in graph}
found_cycle = [False]
subgraph = graph
if root is not None:
try:
subgraph = graph[root]
except KeyError as e:
raise(e)
for u in subgraph:
if color[u] == "white":
dfs_visit(graph, u, color, L, found_cycle)
if found_cycle[0]:
break
if found_cycle[0]:
L = []
L.reverse()
return L
def dfs_visit(graph, u, color, L, found_cycle):
if found_cycle[0]:
return
color[u] = "gray"
for v in graph[u]:
if color[v] == "gray":
print('Found cycle by {}'.format(u))
found_cycle[0] = True
return
if color[v] == "white":
dfs_visit(graph, v, color, L, found_cycle)
color[u] = "black"
L.append(u)