gpt4 book ai didi

python - Monty Hall 模拟器有一个错误的结果

转载 作者:太空宇宙 更新时间:2023-11-04 02:50:39 24 4
gpt4 key购买 nike

我想做一些看似简单的事情,同时通过代码证明 Monty Hall,遗憾的是我得到的不是问题的证明,而是完全相反的。无论我是否切换,我在 10000 次模拟中获胜的几率约为 33%。你能检查一下代码,看看它有什么问题吗?请记住,我是一名网络开发人员,所以我的 Python 技能不是很好,而且代码可能看起来不太好(例如,我制作了一个 removable_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)))

switch=False 时,它给了我 0.3332switch=True 时,它给了我 0.6738,我猜这是相当证实了 Monty Hall 的解决方案:)

关于python - Monty Hall 模拟器有一个错误的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43987782/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com