I have been asked to model the monty hall problem for my computer science homework. It was going rather well, until i got he error IndexError: pop index out of range
. I know my code is probably rather sloppy and horrible for all you actual programmers out there, so I'm sorry if you have a hard time making sense of this. I am only looking for solutions for the index error, and please try to not make them too complicated- this is the first time I have used python after 6 months off of school. Any help is much appreciated.
import random
import time
wins_switch = 0
losses_switch = 0
total_switch = 0
wins_stick = 0
losses_stick = 0
total_stick = 0
#while True :
print ("Monty hall problem model")
global doors
doors = [0, 0, 1]
which = random.randint(0,2)
print ("This is the door that has been chosen: " +(str(which)))
stick_or_switch = random.randint(0,1)
if which == 0:
doors.pop(1)
print("Door 1 has been removed")
print (doors)
if stick_or_switch == 0:
print("The computer has decided to stick with door 0")
print("Therefore, that is a loss")
doors.pop(2)
losses_stick =+1
print(doors)
else:
print("The computer has decided to switch")
print("Therefore that is a win")
doors.pop(0)
wins_switch = +1
print(doors)
elif which == 1:
doors.pop(0)
print ("Door 0 has been removed")
print(doors)
if stick_or_switch == 0:
print("The computer has decided to stick with door 1")
print("Therefore, that is a loss")
doors.pop(2)
losses_stick =+1
print(doors)
else:
print("The computer has decided to switch to door ")
print("Therefore that is a win")
doors.pop(2)
wins_switch = +1
print(doors)
else:
random_door = random.randint(0,1)
doors.pop(random_door)
print ("Door " + str(random_door) + " has been removed")
if random_door == 0:
if stick_or_switch == 0:
print("The computer had decided to stick with door 2")
print("Therefore, that is a win")
doors.pop(1)
wins_stick=+1
print(doors)
else:
print("The computer has decided to switch")
print("Therefore that is a loss")
doors.pop(2)
losses_switch =+1
print(doors)
else:
if stick_or_switch == 0:
print("The computer has decided to stick with door 2 ")
print("Therefore, that is a win")
doors.pop(0)
wins_stick=+1
print(doors)
else:
print("The computer has decided to switch")
print("Therefore that is a loss")
doors.pop(2)
losses_switch =+1
print(doors)
print (doors)
Have a look at the line number where the error occurs... It will give you hints.
Looking at your code what happens (most likely) is that you "pop" a door out, thus you have only 2 doors left, and then I guess, you try to pop the third door (whose index is 2
, i.e. you use .pop(2)
) and you get this error because you have only two doors left so there is no such third door.