269
|
1
|
|
2 class Graph:
|
|
3 """
|
|
4 Generic graph base class.
|
|
5 Can dump to graphiz dot format for example!
|
|
6 """
|
|
7 def __init__(self):
|
|
8 self.nodes = []
|
|
9 self.edges = []
|
|
10
|
|
11 def newNode(self):
|
|
12 n = Node(self)
|
|
13 self.nodes.append(n)
|
|
14 return n
|
|
15
|
|
16 def addEdge(self, n, m):
|
|
17 """ Add an edge from n to m """
|
|
18 if (n, m) not in self.edges and (m, n) not in self.edges:
|
|
19 self.edges.append((n, m))
|
|
20 n.succ.append(m)
|
|
21 m.pred.append(n)
|
|
22
|
|
23 def delEdge(self):
|
|
24 # TODO
|
|
25 pass
|
|
26
|
|
27 def to_dot(self, f):
|
|
28 """ Generate graphviz dot representation """
|
|
29 print('digraph G {', file=f)
|
|
30 for node in self.nodes:
|
|
31 print('{} [label="{}" shape=box3d];'.format(id(node), node), file=f)
|
|
32 for n, m in self.edges:
|
|
33 print('{} -> {};'.format(id(n), id(m)), file=f)
|
|
34 print('}', file=f)
|
|
35
|
|
36
|
|
37 class Node:
|
|
38 """
|
|
39 Node in a graph.
|
|
40 """
|
|
41 def __init__(self, g):
|
|
42 self.g = g
|
|
43 self.succ = []
|
|
44 self.pred = []
|
|
45
|
270
|
46 @property
|
|
47 def Adj(self):
|
|
48 return set(self.succ) | set(self.pred)
|
|
49
|
|
50
|