Created
October 6, 2012 00:23
-
-
Save hoskeri/3843212 to your computer and use it in GitHub Desktop.
Graph implementation experiments.
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
#!/usr/bin/python | |
from collections import defaultdict | |
import user | |
import random | |
class Graph: | |
def __init__(self): | |
self._vertices = set() | |
self._edges = defaultdict(list) | |
def add_vertex(self, data): | |
print 'adding vertex', data | |
self._vertices.add(data) | |
def add_edge(self, data1, data2, cost, reverse=True): | |
print 'adding egde,', data1, data2, cost | |
if not data1 in self._vertices: raise Exception("no such vertex %s", data1) | |
if not data2 in self._vertices: raise Exception("no such vertex %s", data2) | |
self._edges[data1].append((data2, cost, )) | |
if reverse: | |
self.add_edge(data2, data1, cost, reverse=False) | |
def edges(self, data): | |
return self._edges[data] | |
def to_dot(self): | |
x = "digraph G { \n" | |
for f, es in self._edges.iteritems(): | |
for e in es: | |
t, c = e | |
x += " %s -> %s [label=%s];\n" % (f, t, c) | |
x += "}" | |
return x | |
g = Graph() | |
# vertices | |
CARDS = [chr(x) for x in range(ord('A'), ord('G') + 1)] | |
# so we can use random.choice, FIXME. | |
COSTS = range(1, 101) | |
for x in CARDS: g.add_vertex(x) | |
for i in range(1, 10): | |
g.add_edge(random.choice(CARDS), random.choice(CARDS), random.choice(COSTS), | |
reverse=False) | |
# write out the graphviz file | |
with open('/tmp/g.gv', 'w+') as f: | |
f.write(g.to_dot()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment