[Tutor] What's the best way to model an unfair coin?

Jose Amoreira ljmamoreira at gmail.com
Sun Oct 24 17:46:22 CEST 2010

On Sunday, October 24, 2010 01:18:52 pm Alan Gauld wrote:

> In pseudo code:
> def coinToss(prob = 0.5):
>     rand = random()
>     if rand >= prob: return True
>     else: return False
> print "Heads" if coinToss(6/11) else "Tails"

The only problem with this snippet is integer division: 6/11=0, at least in 
Python 2.6, so that the final line will always print "Heads".

But wait! This is pseudo code! Ah, OK. Then 6/11=0.545454..., and Alan was 
right (as usual).
This pseudo code snippet is almost Python code. It looks like Python, it 
smells like Python, it even runs as Python, if you import random from random 
Python really is executable pseudo code!
Jose Amoreira

More information about the Tutor mailing list