Is this a good or bad 'simulation' for Monty Hall? How come? Is this a good or bad 'simulation' for Monty Hall? How come? python python

Is this a good or bad 'simulation' for Monty Hall? How come?


Your solution is fine, but if you want a stricter simulation of the problem as posed (and somewhat higher-quality Python;-), try:

import randomiterations = 100000doors = ["goat"] * 2 + ["car"]change_wins = 0change_loses = 0for i in xrange(iterations):    random.shuffle(doors)    # you pick door n:    n = random.randrange(3)    # monty picks door k, k!=n and doors[k]!="car"    sequence = range(3)    random.shuffle(sequence)    for k in sequence:        if k == n or doors[k] == "car":            continue    # now if you change, you lose iff doors[n]=="car"    if doors[n] == "car":        change_loses += 1    else:        change_wins += 1print "Changing has %s wins and %s losses" % (change_wins, change_loses)perc = (100.0 * change_wins) / (change_wins + change_loses)print "IOW, by changing you win %.1f%% of the time" % perc

a typical output is:

Changing has 66721 wins and 33279 lossesIOW, by changing you win 66.7% of the time


You mentioned that all the choices are hardcoded in. But if you look closer, you'll notice that what you think are 'choices' are actually not choices at all. Monty's decision is without loss of generality since he always chooses the door with the goat behind it. Your swapping is always determined by what Monty chooses, and since Monty's "choice" was actually not a choice, neither is yours. Your simulation gives the correct results..


I like something like this.

#!/usr/bin/python                                                                                                            import randomCAR   = 1GOAT  = 0def one_trial( doors, switch=False ):    """One trial of the Monty Hall contest."""    random.shuffle( doors )    first_choice = doors.pop( )    if switch==False:        return first_choice    elif doors.__contains__(CAR):        return CAR    else:        return GOATdef n_trials( switch=False, n=10 ):    """Play the game N times and return some stats."""    wins = 0    for n in xrange(n):        doors = [CAR, GOAT, GOAT]        wins += one_trial( doors, switch=switch )    print "won:", wins, "lost:", (n-wins), "avg:", (float(wins)/float(n))if __name__=="__main__":    import sys    n_trials( switch=eval(sys.argv[1]), n=int(sys.argv[2]) )$ ./montyhall.py True 10000won: 6744 lost: 3255 avg: 0.674467446745