Mercurial > public > think_complexity
comparison 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 |
comparison
equal
deleted
inserted
replaced
34:66a5e7f7c10f | 35:10db8c3a6b83 |
---|---|
5 | 5 |
6 Copyright 2011 Allen B. Downey. | 6 Copyright 2011 Allen B. Downey. |
7 Distributed under the GNU General Public License at gnu.org/licenses/gpl.html. | 7 Distributed under the GNU General Public License at gnu.org/licenses/gpl.html. |
8 """ | 8 """ |
9 import itertools | 9 import itertools |
10 from collections import deque | 10 from collections import deque, Counter |
11 | 11 |
12 | 12 |
13 class GraphError(Exception): | 13 class GraphError(Exception): |
14 """Exception for Graph errors""" | 14 """Exception for Graph errors""" |
15 pass | 15 pass |
233 visited = self.bfs(vs[0]) | 233 visited = self.bfs(vs[0]) |
234 # See if all nodes have been visited | 234 # See if all nodes have been visited |
235 return len(vs) == len(visited) | 235 return len(vs) == len(visited) |
236 | 236 |
237 return False # Graph is empty | 237 return False # Graph is empty |
238 | |
239 def get_p(self): | |
240 """This method returns a dictionary of probabilities where each key is | |
241 the connectivity k and the value is the probability [0-1] for this | |
242 graph. | |
243 | |
244 """ | |
245 # First, for each vertex, count up how many neighbors it has | |
246 vs = self.vertices() | |
247 | |
248 c = Counter() | |
249 for v in vs: | |
250 n = len(self.out_vertices(v)) | |
251 c[n] += 1 | |
252 | |
253 n = len(vs) | |
254 if n > 0: | |
255 for k in c: | |
256 c[k] = float(c[k]) / n | |
257 | |
258 return c | |
238 | 259 |
239 | 260 |
240 def main(script, *args): | 261 def main(script, *args): |
241 import pprint | 262 import pprint |
242 | 263 |