From 426dbf8d1c46780444ecab677fd8b7315b471860 Mon Sep 17 00:00:00 2001 From: "Adam Hoelscher, ASA, MAAA" Date: Sat, 14 Sep 2019 14:29:04 -0700 Subject: [PATCH] Clean up Matt's drunken coding added shebang replaced C-style looping with pythonic looping put in version checking so it runs in python3 also added doc strings poked fun at Matt, even though I'm actually really jealous: I need more friends who want to sit around a pub and write python with me on random nights --- frog-2.py | 70 +++++++++++++++++++++++++++++-------------------------- 1 file changed, 37 insertions(+), 33 deletions(-) diff --git a/frog-2.py b/frog-2.py index c0b0eec..e010b2c 100644 --- a/frog-2.py +++ b/frog-2.py @@ -1,38 +1,42 @@ +#! python +# I wrote this quickly in a pub +# Don't judge me +# You're not a bad person Matt. Say it with me... "My code is ugly, but I'm ok" --Adam + +from random import randrange +import sys + +# if running in python 2, make range makes a list and xrange makes a generator +# generators are faster than large lists, so use xrange +if sys.version_info[0] == 2: + range = xrange + def frog(final_dist=100,max=6): + ''' + Simulate a large number of frogs crossing a large number of rivers. Default + values result in 100 million simulations. - # I wrote this quickly in a pub - # Don't judge me + final_dist: int, default=100 + This is the width of the largest river that will be simulated - total_dist = 1 - - while total_dist <= final_dist: - - import random - - cap = 10**max + max: int, default=6 + This is the base ten log of the max number of trials at each distance. + The default of 6 therefore results in 1_000_000 trials per width of + river + ''' - trials = 0 - total_leaps = 0 - - while trials <= cap: - - dist = total_dist - leaps = 0 - - while dist > 0: - this_jump = int(random.random()*(dist)+1) - dist -= this_jump - leaps += 1 - - total_leaps += leaps - - trials += 1 - - print "{0}\t{1}".format(total_dist,(total_leaps*1.0)/trials) - - total_dist += 1 - - return "DONE" - + cap = 10 ** max + + def trial(total_dist): + ''' + Simulate a frog crossing a river once. + ''' + leaps = 0 + while total_dist: + total_dist -= randrange(1, total_dist+1) + leaps += 1 + return leaps - \ No newline at end of file + for total_dist in range(1, final_dist + 1): + avg_leaps = 1.0 * sum(trial(total_dist) for _ in range(cap)) / cap + print("{0}\t{1}".format(total_dist, avg_leaps))