changeset 6:950a34c7e26b

Update for section 2.2, exercise 4, random graphs.
author Brian Neal <bgneal@gmail.com>
date Sat, 01 Dec 2012 18:17:58 -0600
parents 8e44660965ef
children 69e5977417b3
files Graph.py RandomGraph.py
diffstat 2 files changed, 60 insertions(+), 8 deletions(-) [+]
line wrap: on
line diff
--- a/Graph.py	Sat Dec 01 16:51:39 2012 -0600
+++ b/Graph.py	Sat Dec 01 18:17:58 2012 -0600
@@ -55,16 +55,18 @@
     For vertices a and b, graph[a][b] maps
     to the edge that connects a->b, if it exists."""
 
-    def __init__(self, vs=[], es=[]):
+    def __init__(self, vs=None, es=None):
         """Creates a new graph.
         vs: list of vertices;
         es: list of edges.
         """
-        for v in vs:
-            self.add_vertex(v)
+        if vs:
+            for v in vs:
+                self.add_vertex(v)
 
-        for e in es:
-            self.add_edge(e)
+        if es:
+            for e in es:
+                self.add_edge(e)
 
     def add_vertex(self, v):
         """Add a vertex to the graph."""
@@ -137,9 +139,7 @@
 
         # For each combination of 2 vertices, create an edge between them:
         for v, w in itertools.combinations(self.iterkeys(), 2):
-            e = Edge(v, w)
-            self[v][w] = e
-            self[w][v] = e
+            self.add_edge(Edge(v, w))
 
     def add_regular_edges(self, k):
         """Makes the graph regular by making every vertex have k edges.
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/RandomGraph.py	Sat Dec 01 18:17:58 2012 -0600
@@ -0,0 +1,52 @@
+"""This module contains the RandomGraph class.
+
+"""
+import random
+import itertools
+
+from Graph import Graph, Edge
+
+
+class RandomGraph(Graph):
+    """A RandomGraph is a Graph that adds a method to generate random edges."""
+
+    def add_random_edges(self, p=0.5):
+        """This method first removes all edges, then adds edges at random such
+        that the probability is p that there is an edge between any two nodes.
+
+        p must be a float between 0 and 1, inclusive.
+
+        """
+        self.remove_all_edges()
+
+        # For each combination of 2 vertices, create an edge between them if we
+        # select a random number [0.0, 1.0) that is less than p.
+        for v, w in itertools.combinations(self.iterkeys(), 2):
+            if random.random() <= p:
+                self.add_edge(Edge(v, w))
+
+
+if __name__ == '__main__':
+    import string
+    import sys
+    from Graph import Vertex
+    from GraphWorld import GraphWorld, CircleLayout
+
+    def main(script_name, n=10, p=0.5):
+
+        n = int(n)
+        p = float(p)
+
+        labels = string.ascii_lowercase + string.ascii_uppercase
+        vs = [Vertex(c) for c in labels[:n]]
+
+        g = RandomGraph(vs)
+        g.add_random_edges(p)
+        layout = CircleLayout(g)
+
+        gw = GraphWorld()
+        gw.show_graph(g, layout)
+        gw.mainloop()
+
+    main(*sys.argv)
+