3 ms·
The answer to any question of this form is: Unless you happen to be able to solve it quickly by doing mathematics, simulate! import random def one(): n
by gjm11 16y ago
The answer to any question of this form is: Unless you happen to be able to solve it quickly by doing mathematics, simulate!
import random
def one():
n = 0
while True:
k = random.randint(0,2)
if k==0: return n
n += k
def many(k):
return sum(one() for i in range(n)) / float(n)
[many(1000) for i in range(10)]
many(100000)
will make it pretty easy to guess what the right answer is.
The previous-but-one posting on the same blog has a distinctly more difficult question: repeatedly pick independent random numbers uniform on [0,1]; stop when your latest number is smaller than some previous one; what's the average number of numbers you have to pick? Exercise for the reader: provide the appropriate definition of one() to make the calculation above work. It's only a few lines.
(Mathematically expert readers will be able to solve both these problems rigorously and quickly without simulating. But if such a problem comes up in a context where you actually care about the answer you'd do well to do the simulation anyway, since it's an easy way to check your reasoning.)
- ojbyrne 16y agoI know you just tossed off that code, but I wanted to run it. I think n should have been k in the line "return sum(one() for i in range(n)) / float(n)"
- gjm11 16y agoActually it should have been "def many(n)" instead of "def many(k)" :-), but yes. Thanks for the bugfix. Too late to edit it in, alas.