Created
April 6, 2011 10:46
-
-
Save samwho/905459 to your computer and use it in GitHub Desktop.
A simulation, in Python, of the Variable Change problem as explained in the movie "21".
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import random | |
def get_choices(): | |
'''Generates a list of size 3 that represents the doors. 0 is a loss (goat) | |
while 1 is a win (car). 1 door will have a 1 in it, the other two will have | |
0s.''' | |
choices = [0, 0, 0] | |
choices[random.randint(0, 2)] = 1 | |
return choices | |
def remove_choice(doors, choice): | |
'''Takes the list of doors and the players current choice and returns a | |
door number that is neither the players current choice or the right | |
door.''' | |
index = random.randint(0, 2) | |
while (doors[index] == 1 or index == choice): | |
index = random.randint(0, 2) | |
return index | |
def switch_choice(choice, removed): | |
'''Takes the players current choice and the door that has already been | |
opened and revealed to have nothing behind it and returns the last remaining | |
door. Hence a switched choice.''' | |
if 0 != choice and 0 != removed: | |
return 0 | |
if 1 != choice and 1 != removed: | |
return 1 | |
if 2 != choice and 2 != removed: | |
return 2 | |
wins = 0 | |
losses = 0 | |
for i in range(0, 10000): | |
doors = get_choices() | |
#print "Doors: " + str(doors) | |
choice = random.randint(0, 2) | |
#print "Initial choice: " + str(choice+1) | |
opened = remove_choice(doors, choice) | |
#print "Host opened door: " + str(opened+1) | |
choice = switch_choice(choice, opened) | |
#print "Choice switched to: " + str(choice+1) | |
if doors[choice] == 1: | |
wins += 1 | |
else: | |
losses += 1 | |
print "Wins: " + str(wins) + "\tLosses: " + str(losses) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment