montehall.py


Below is the syntax highlighted version of montehall.py from §1.3 Conditionals and Loops.


#-----------------------------------------------------------------------
# montehall.py
#-----------------------------------------------------------------------

import stdio
import sys
import random

# Accept integer n as a command-line argument. Play the Monte Hall game
# n times with the switching strategy and report the fraction of games
# won to standard output. Note:  The true winning probability is 2/3.

n = int(sys.argv[1])  # number of trials
wins = 0              # number of times you win by switching

# Repeat the experiment n times;
for i in range(0, n):

    # Host hides prize behind 1 of 3 doors uniformly at random.
    prize  = random.randrange(0, 3)

    # Contestant selects 1 of 3 doors uniformly at random.
    choice = random.randrange(0, 3)

    # At random, host reveals an unchosen door not containing prize.
    reveal = random.randrange(0, 3)
    while (reveal == choice) or (reveal == prize):
        reveal = random.randrange(0, 3)

    # Hack to compute the remaining door which contestent switches to.
    other = 0 + 1 + 2 - reveal - choice

    # Switching leads to a win?
    if other == prize:
        wins += 1

# Avoid integer division.
fractionWon = float(wins) / float(n)

# Write the result.
stdio.writeln('Fraction of games won = ' + str(fractionWon))

#-----------------------------------------------------------------------

# python montehall.py 100
# Fraction of games won = 0.62

# python montehall.py 1000
# Fraction of games won = 0.666

# python montehall.py 10000
# Fraction of games won = 0.6562

# python montehall.py 100000
# Fraction of games won = 0.6697


Copyright © 2000–2015, Robert Sedgewick, Kevin Wayne, and Robert Dondero.
Last updated: Fri Oct 20 20:45:16 EDT 2017.