Skip to content

Commit f4ff37d

Browse files
author
Michael Hammann
committed
feat: add graphutils to detect cyclical process dependencies
1 parent 9bb5592 commit f4ff37d

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

supervisor/graphutils.py

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
from collections import defaultdict
2+
3+
class Graph():
4+
def __init__(self,vertices):
5+
self.graph = defaultdict(list)
6+
self.V = vertices
7+
8+
def addEdge(self,u,v):
9+
self.graph[u].append(v)
10+
11+
def cyclic(self):
12+
"""Return True if the directed graph has a cycle.
13+
The graph must be represented as a dictionary mapping vertices to
14+
iterables of neighbouring vertices. For example:
15+
16+
>>> cyclic({1: (2,), 2: (3,), 3: (1,)})
17+
True
18+
>>> cyclic({1: (2,), 2: (3,), 3: (4,)})
19+
False
20+
21+
"""
22+
path = set()
23+
visited = set()
24+
25+
def visit(vertex):
26+
if vertex in visited:
27+
return False
28+
visited.add(vertex)
29+
path.add(vertex)
30+
for neighbour in self.graph.get(vertex, ()):
31+
if neighbour in path or visit(neighbour):
32+
return True
33+
path.remove(vertex)
34+
return False
35+
36+
return any(visit(v) for v in self.graph)

0 commit comments

Comments
 (0)