diff Graph.py @ 35:10db8c3a6b83

Chapter 5.5, exercise 6, #2: plot P(k) vs. k for a WS graph.
author Brian Neal <bgneal@gmail.com>
date Wed, 09 Jan 2013 20:51:16 -0600
parents 84e183b40c63
children 305cc03c2750
line wrap: on
line diff
--- a/Graph.py	Wed Jan 09 20:19:49 2013 -0600
+++ b/Graph.py	Wed Jan 09 20:51:16 2013 -0600
@@ -7,7 +7,7 @@
 Distributed under the GNU General Public License at gnu.org/licenses/gpl.html.
 """
 import itertools
-from collections import deque
+from collections import deque, Counter
 
 
 class GraphError(Exception):
@@ -236,6 +236,27 @@
 
         return False        # Graph is empty
 
+    def get_p(self):
+        """This method returns a dictionary of probabilities where each key is
+        the connectivity k and the value is the probability [0-1] for this
+        graph.
+
+        """
+        # First, for each vertex, count up how many neighbors it has
+        vs = self.vertices()
+
+        c = Counter()
+        for v in vs:
+            n = len(self.out_vertices(v))
+            c[n] += 1
+
+        n = len(vs)
+        if n > 0:
+            for k in c:
+                c[k] = float(c[k]) / n
+
+        return c
+
 
 def main(script, *args):
     import pprint