One last comment I swear. The biased_coin() function can also be generalized to use any input and output probability, like this:
def biased_coin(flip, p, q):
'''Given a function flip() that returns 1 with probability p and 0 otherwise,
returns 1 with probability q and 0 otherwise.'''
o = flip()
if p > q:
return 0 if o == 0 else biased_coin(flip, p, q/p)
if p < q:
return 1 if o == 1 else biased_coin(flip, p, (q - p)/(1 - p))
return o
One last comment I swear. The
biased_coin()function can also be generalized to use any input and output probability, like this: