Return to Snippet

Revision: 62494
at February 27, 2013 08:46 by csrsen


Initial Code
#---------------------------------
# The Monty Hall Problem
#---------------------------------

import random

pickcount = 0
newpickcount = 0
i = 0
counter = 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)

Initial URL

                                

Initial Description
A proof of the Monty Hall problem written in Python.

Initial Title
Monty Hall problem

Initial Tags

                                

Initial Language
Python