Mercurial > lcfOS
view python/graph.py @ 271:cf7d5fb7d9c8
Reorganization
author | Windel Bouwman |
---|---|
date | Tue, 20 Aug 2013 18:56:02 +0200 |
parents | cdc76d183bcc |
children | ea93e0a7a31e |
line wrap: on
line source
class Graph: """ Generic graph base class. Can dump to graphiz dot format for example! """ def __init__(self): self.nodes = [] self.edges = [] def newNode(self): n = Node(self) self.nodes.append(n) return n def addEdge(self, n, m): """ Add an edge from n to m """ if (n, m) not in self.edges and (m, n) not in self.edges: self.edges.append((n, m)) n.succ.append(m) m.pred.append(n) def delEdge(self): # TODO pass def to_dot(self, f): """ Generate graphviz dot representation """ print('digraph G {', file=f) for node in self.nodes: print('{} [label="{}" shape=box3d];'.format(id(node), node), file=f) for n, m in self.edges: print('{} -> {};'.format(id(n), id(m)), file=f) print('}', file=f) class Node: """ Node in a graph. """ def __init__(self, g): self.g = g self.succ = [] self.pred = [] @property def Adj(self): return set(self.succ) | set(self.pred)