Mercurial > public > think_complexity
changeset 9:9f1fccc13991
Added a program that does 2.3 exercise 6 (Paul Erdos).
author | Brian Neal <bgneal@gmail.com> |
---|---|
date | Mon, 03 Dec 2012 19:40:26 -0600 |
parents | 1defe6fcf9d3 |
children | aea27d10dd18 |
files | ch2ex6.py |
diffstat | 1 files changed, 55 insertions(+), 0 deletions(-) [+] |
line wrap: on
line diff
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/ch2ex6.py Mon Dec 03 19:40:26 2012 -0600 @@ -0,0 +1,55 @@ +"""ch2ex6.py - Program for Chapter 2.5, exercise 6. + +This program generates random graphs with parameters n and p and computes the +fraction of them that are connected. + +""" +import string + +from Graph import Vertex +from RandomGraph import RandomGraph + + +LABELS = string.letters + string.punctuation + +def test_graph(n, p): + """Generate a RandomGraph with parameters n & p and return True if the + graph is connected, False otherwise. + + """ + vs = [Vertex(c) for c in LABELS[:n]] + g = RandomGraph(vs) + g.add_random_edges(p) + return g.is_connected() + + +def test_p(n, p, num): + """Generate num RandomGraphs with parameters n & p and return the number + of graphs that are connected. + + """ + count = 0 + for i in range(num): + if test_graph(n, p): + count += 1 + + return count + + +def main(script_name, n=26, p=0.1, num=1, *args): + """Generate num RandomGraphs with parameters n & p and print out the number + of graphs that are connected. + + """ + + n = int(n) + p = float(p) + num = int(num) + + count = test_p(n, p, num) + print count + + +if __name__ == '__main__': + import sys + main(*sys.argv)