From ee6e59f9d9c94b3a11667e4efb5d3b634bf8cf6e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Eray=20=C3=96zkural?= Date: Mon, 18 Jul 2005 13:11:39 +0000 Subject: [PATCH] * cycle var mi bakan code yaz. testini de yap. testisini de. --- pisi/graph.py | 20 ++++++++++++++++---- tests/graphtests.py | 12 ++++++------ 2 files changed, 22 insertions(+), 10 deletions(-) diff --git a/pisi/graph.py b/pisi/graph.py index e0befeaf..e0dd636f 100644 --- a/pisi/graph.py +++ b/pisi/graph.py @@ -1,5 +1,8 @@ # the most simple minded digraph class ever +class CycleError: + pass + class digraph(object): def __init__(self): @@ -66,7 +69,7 @@ class digraph(object): self.d = {} self.f = {} for u in self.__v: - self.color[u] = 'w' + self.color[u] = 'w' # mark white (unexplored) self.p[u] = None self.time = 0 for u in self.__v: @@ -74,17 +77,26 @@ class digraph(object): self.dfs_visit(u, finish_hook) def dfs_visit(self, u, finish_hook): - self.color[u] = 'g' + self.color[u] = 'g' # mark green (discovered) self.d[u] = self.time = self.time + 1 for v in self.adj(u): - if self.color[v] == 'w': + if self.color[v] == 'w': # explore unexplored vertices self.p[v] = u self.dfs_visit(v, finish_hook) - self.color[u] = 'b' + elif self.color[v] == 'g': # cycle detected + raise CycleError + self.color[u] = 'b' # mark black (completed) if finish_hook: finish_hook(u) self.f[u] = self.time = self.time + 1 + def cycle_free(self): + try: + self.dfs() + return True + except CycleError: + return False + def topological_sort(self): l = [] self.dfs(lambda u: l.append(u)) diff --git a/tests/graphtests.py b/tests/graphtests.py index 469e5b3d..826e7085 100644 --- a/tests/graphtests.py +++ b/tests/graphtests.py @@ -7,15 +7,15 @@ from pisi.config import config class GraphTestCase(unittest.TestCase): def setUp(self): - g0 = graph.digraph() - g0.from_list([ (1,2), (1,3), (2,3), (3,4), (4, 5), (4,1)]) + self.g0 = graph.digraph() + self.g0.from_list([ (1,2), (1,3), (2,3), (3,4), (4, 5), (4,1)]) - g1 = graph.digraph() - g1.from_list([ (0,2), (0,3), (3,4), (2,4), (0,5), (5,4) ]) - self.g1 = g1 + self.g1 = graph.digraph() + self.g1.from_list([ (0,2), (0,3), (3,4), (2,4), (0,5), (5,4) ]) def testCycle(self): - pass + self.assert_(not self.g0.cycle_free()) + self.assert_(self.g1.cycle_free()) def testTopologicalSort(self): order = self.g1.topological_sort()