Created
June 1, 2017 12:44
-
-
Save lrodorigo/39af7ebf1c22b2c5917ff70b364f1c42 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import random | |
import networkx as nx | |
from networkx.exception import NetworkXNoCycle | |
class Node(object): | |
def __init__(self, name, dependencies): | |
self.name = name | |
self.dependencies = dependencies | |
def __str__(self): | |
return "Name: %s - Depencencies: %s" % (self.name, [x.name for x in self.dependencies]) | |
def cycle_detector(node): | |
visiting = {} | |
def _cycle_detector(node): | |
if node in visiting: | |
raise ImportError("Depedency Cycle") | |
visiting[node] = True | |
[_cycle_detector(n) for n in node.dependencies] | |
_cycle_detector(node) | |
def generate_graph(size): | |
nodes = [Node(i, None) for i in range(size)] | |
for i in range(size): | |
nodes[i].dependencies = [x for x in nodes if random.random() > 0.99 and nodes[i] != x] | |
print "\n".join([str(x) for x in nodes]) | |
return nodes | |
SIZE = 60 | |
nodes = generate_graph(SIZE) | |
found_cycle = False | |
for i in range(SIZE): | |
try: | |
cycle_detector(nodes[i]) | |
except ImportError: | |
print "Dependency Cycle for %s" % i | |
found_cycle = True | |
g = nx.DiGraph() | |
[g.add_node(x.name) for x in nodes] | |
for x in nodes: | |
[g.add_edge(x.name, y.name) for y in x.dependencies] | |
try: | |
print nx.find_cycle(g, orientation='original') | |
except Exception as ex: | |
if found_cycle: | |
print "Errore!!" | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment