random.random()
returns a uniformly distributed pseudo-random floating point number in the range [0, 1). This number is less than a given number p
in the range [0,1) with probability p
. Thus:
def flip(p):
return 'H' if random.random() < p else 'T'
Some experiments:
>>> N = 100
>>> flips = [flip(0.2) for i in xrange(N)]
>>> float(flips.count('H'))/N
0.17999999999999999 # Approximately 20% of the coins are heads
>>> N = 10000
>>> flips = [flip(0.2) for i in xrange(N)]
>>> float(flips.count('H'))/N
0.20549999999999999 # Better approximation