我想做些看似简单的事情,同时用代码证明Monty Hall,可悲的是我得到的不是问题的证明,而是完全相反的证明。无论我是否进行切换,我在10000次模拟中都能获得〜33%的获胜几率。您可以检查一下代码,看看有什么问题吗?请记住,我是一个Web开发人员,所以我的Python技能不是很好,并且代码可能看起来并不完美(例如,我列出了一个removeable_doors列表,其中只有一个变量可以正常工作)。干杯!
import random
av_doors = [1, 2, 3]
door_v = [1, 2, 3]
removable_doors = [1, 2, 3]
score = 0
loses = 0
door = int(input("Choose your door (1-3)"))
pick = int(door)-1
dec = input("Stay or switch? (0/1)")
n = 0
while n < 10000:
removable_doors = [1, 2, 3]
av_doors = [1, 2, 3]
val = random.randint(1,3)
if val == 1:
door_v[0] = 1
door_v[1] = 0
door_v[2] = 0
removable_doors.remove(1)
elif val == 2:
door_v[0] = 0
door_v[1] = 1
door_v[2] = 0
removable_doors.remove(2)
elif val == 3:
door_v[0] = 0
door_v[1] = 0
door_v[2] = 1
removable_doors.remove(3)
try:
removable_doors.remove(int(door))
except:
pass
av_doors.remove(door)
if len(removable_doors) == 2:
rand_door = random.randint(0,1)
if rand_door == 0:
del av_doors[0]
elif rand_door ==1:
del av_doors[1]
else:
del av_doors[0]
if dec == "1":
door = av_doors[0]
else:
pass
pick = door-1
if door_v[pick] == 1:
score+=1
else:
loses+=1
n+=1
print(score)
print(loses)
最佳答案
您的主人有时会移开一扇门,门后面有辆汽车……这是一个可行的解决方案,并且(我认为)写得更好一些,同时保留了您的结构(在python3中,但这不会引起麻烦):
import random
win = 0
lose = 0
switch = int(input("Stay or switch? (0-stay/1-switch):")) == 1
n = 0
while n < 10000:
# Init
door_values = [0, 0, 0]
removable_doors = [0, 1, 2]
available_doors = [0, 1, 2]
# Placing the reward somewhere
car_place = random.randint(0, 2)
door_values[car_place] = 1
removable_doors.remove(car_place)
# Choose a door
door_chosen = random.randint(0, 2)
available_doors.remove(door_chosen)
if door_chosen != car_place:
removable_doors.remove(door_chosen)
# Host removes a door that does not have the car and has not been chosen by the player
door_removed_by_host = removable_doors[random.randint(0, len(removable_doors)-1)]
available_doors.remove(door_removed_by_host)
# Switch if specified
if switch:
assert(len(available_doors) == 1)
door_chosen = available_doors[0]
# Check the result
if car_place == door_chosen:
win += 1
else:
lose += 1
n+=1
print('win=%s'%str(win))
print('lose=%s'%str(lose))
print('ratio=%s'%str(win/(win+lose)))
当
0.3332
,switch=False
表示0.6738
时,它给了我switch=True
,我想这肯定是Monty Hall的解决方案:)关于python - Monty Hall模拟器的结果有误,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43987782/