I want to see if the strategy of making each prisoner first pick the box with his own number on it and then open the box bearing the number contained in the previous one (and so forth) actually results in success 31% of the time. Thus, I wanted to recreate the strategy in Python and iterate it 1000 times. (Note that I’m storing the outcomes of each trial in a list to then be summed, although I’m not summing it here yet).
import random
boxesnum = list(range(100)) #generate list of 100 boxes
outcomes = [] #create empty list to store outcome of each iteration
for i in range(1000): #iterate process 1000 times
random1 = list(range(100))
random.shuffle(random1) #generate list of numbers from 0 to 99 and shuffle them randomly
boxes = dict(zip(boxesnum,random1)) #create dictionary mapping each box to a number randomly shuffled
lastprisoner = 0 #initialize count of prisoners who successfully find their number in the boxes
for prisoner in boxesnum:
boxopen = prisoner #let prisoner start "opening" boxes from the one with his own number (prisoners numbered from 0 to 99)
boxesopened = 0 #initialize count for number of boxes opened by each prisoner
while boxesopened < 50: #let prisoner open up to 50 boxes
if boxopen == random1[boxopen]: #if the prisoner opens a box with his own number, skip to next prisoner and add 1 to count of successful prisoners
lastprisoner += 1
break
else:
boxopen = random1[boxopen] #next box the prisoner opens is box #(number contained in previous box)
boxesopened += 1 #update count of boxes opened by the prisoner
else:
print("All prisoners are dead!") #if prisoner has to open more than 50 boxes, stop iteration and all prisoners die
outcomes.append(0) #add 0 to list of outcomes of each trial
break
if lastprisoner == 100:
print("Success!")
outcomes.append(1) #if all prisoners are successful, add 1 to list of outcomes of each trial
print(outcomes)
The problem is that it only returns failures (all prisoners die in each of the 100 trials), while the strategy implemented should have a success rate of 31%.
I really cannot understand why this code isn’t working.
Could there be a problem with the way the “shuffle” method is randomizing the content of the boxes?
Note: I’m fairly new to python and programming in general.
6
You checked that the box opened was the same box, not that it was the prisoner’s box. Change the line if boxopen == random1[boxopen]:
to if prisoner == random1[boxopen]:
.