I tried to simulate the Monty Hall problem in Python, and ended up with 66% probability after a few attempts. However, the first incorrect attempts were more interesting, as they consistently gave a probability of 55% and 44% respectively.
Here's the code:
import random
from sys import argv
def hall_old():
choices = [0]*3
choices[random.randint(0,2)] = 1
guess = random.randint(0,2)
reveal = (random.randint(1,2)+guess)%3 # This gives ~55%
reveal = 2 - guess # This gives ~44%
if choices[reveal]==1:
return hall()
return choices[3-guess-reveal]==1
def hall(): # This gives 66%
choices = [0]*3
choices[random.randint(0,2)] = 1
guess = 0
for i in range(1,3):
if choices[i]==0:
reveal = i
break
return choices[3-guess-reveal]==1
def main():
times = int(argv[1]) # times game is played
correct = 0
for i in range(0, times):
if hall_old():
correct += 1
print str(correct * 100 / times) + '%'
main()
From what I understand, the function hall_old(), should still give 66% probability when run but for some reason, if you change the way you select the variable reveal then the probability changes. Can anyone explain why this is occurring?
Given a perfect PRNG,
guessinhall_oldshould be a uniformly distributed random number $\in\{0,1,2\}$.With
reveal = (random.randint(1,2)+guess)%3, it should accordingly be thatrevealis uniformly distributed $\in\{0,1,2\}\setminus\{\text{guess}\}$. Note that in this case3-guess-revealis simply the remaining third number (why non call itother?). In $\frac13$ of all cases, you callhall(), which itself seems to returntruewith a probability $\frac 23$. In the remaing $\frac23$ of all cases (namely, whenrevealis not the win), you return ifchoice[other]is true, which shold be so with probability $\frac12$. Hence we expect something like $$\frac13\cdot \frac23 +\frac23\cdot \frac12=\frac 59. $$If you use
reveal = 2-guessinstead, again in $\frac13$ of all cases you returnhall()and in the other $\frac23$ of cases, you return if\choice[1]is true (asguess+revealis definitely $2$). Note that this never the case ifguessis $= 1$ (as it would already have been caught by the firstif). Hence we expect something like $$ \frac 13\cdot \frac 23+\frac 23\cdot \left(\frac 13\cdot 0+\frac 23\cdot \frac12\right)=\frac 49.$$