Posted By

csrsen on 02/27/13

Monty Hall problem

/ Published in: Python

A proof of the Monty Hall problem written in Python.

`#---------------------------------# The Monty Hall Problem#--------------------------------- import random pickcount = 0newpickcount = 0i = 0counter = 100000 def pick1of3():    pick=random.randint(0,2)    return pick while i < counter:# Prize assignment    doors = ['goat','goat','goat']    car = pick1of3()    doors[car] = 'car ' # Contestant choice    firstchoice = pick1of3()    pick = doors[firstchoice] # Monty's reveal    reveal=random.random()     if firstchoice == 0:        if pick=='car ' and reveal < 0.5: Montyshows=doors[1]        elif pick=='car ': Montyshows=doors[2]        elif pick=='goat' and doors[1]=='goat': Montyshows=doors[1]        else: Montyshows=doors[2]     elif firstchoice == 1:        if pick=='car ' and reveal < 0.5: Montyshows=doors[0]        elif pick=='car ': Montyshows=doors[2]        elif pick=='goat' and doors[0]=='goat': Montyshows=doors[0]        else: Montyshows=doors[2]     elif firstchoice == 2:        if pick=='car ' and reveal < 0.5: Montyshows=doors[0]        elif pick=='car ': Montyshows=doors[1]        elif pick=='goat' and doors[0]=='goat': Montyshows=doors[0]        else: Montyshows=doors[1]  # The Switch    if pick==doors[0]:        if Montyshows==doors[1]: newpick=doors[2]        else: newpick=doors[1]     elif pick==doors[1]:        if Montyshows==doors[0]: newpick=doors[2]        else: newpick=doors[0]     else:        if Montyshows==doors[0]: newpick=doors[1]        else: newpick=doors[0]     if pick == 'car ':        pickcount = pickcount + 1     if newpick == 'car ':        newpickcount = newpickcount + 1     i = i + 1 print 'Original Pick is a Car: ',"{0:.3f}%".format(float(pickcount)/counter * 100)print 'Switched Pick is a Car: ',"{0:.3f}%".format(float(newpickcount)/counter * 100)`