python - Monty Hall 模拟器无法正常工作
问题描述
我试图模拟蒙蒂霍尔问题。
首先,我选择了获胜的门并随机选择了一个选项。然后打开一扇不是所选门的门。然后检查是否选中 = 获胜门。如果是,我将 1 添加到不切换点 (b.num)。
然后切换选择,我从门列表中删除了选定的门,并将选择均衡到列表中的唯一项目。然后检查是否选中 = 再次获胜门,如果是,我将 1 添加到切换点 (s.num1)。
问题是切换获胜百分比大致等于 33。它的预期值约为 66。问题出在哪里?
import random
from random import randint
def b():
b.num+=1
b.num=0
def s():
s.num+=1
s.num=0
d=int(input("try count: "))
def a():
winner=randint(1,3)
selection=randint(1,3)
doors=[1,2,3]
doors_to_open=randint(1,2)
if selection == 1:
if doors_to_open==1:
doors.remove(2)
else:
doors.remove(3)
if selection == 2:
if doors_to_open==1:
doors.remove(1)
else:
doors.remove(3)
if selection == 3:
if doors_to_open==1:
doors.remove(1)
else:
doors.remove(2)
if selection == winner:
b()
#print("Not switching win count: ",b.num)
# switch
doors.remove(selection)
selection = doors[0]
if selection == winner:
s()
#print("Switching win count: ",s.num)
for q in range (0,d):
a()
#print("Switching win count: ",s.num)
print("Switching percent: ",(s.num/d)*100)
#print("Not switching win count: ",b.num)
print("Not switching percent: ",(b.num/d)*100)
input()
解决方案
您在调用 s 函数时错过了不等于运算符。如果你添加!在条件。它将修复您的模拟。
import random
from random import randint
def b():
b.num+=1
b.num=0
def s():
s.num+=1
s.num=0
d=int(input("try count: "))
def a():
winner=randint(1,3)
selection=randint(1,3)
doors=[1,2,3]
doors_to_open=randint(1,2)
if selection == 1:
if doors_to_open==1:
doors.remove(2)
else:
doors.remove(3)
if selection == 2:
if doors_to_open==1:
doors.remove(1)
else:
doors.remove(3)
if selection == 3:
if doors_to_open==1:
doors.remove(1)
else:
doors.remove(2)
if selection == winner:
b()
#print("Not switching win count: ",b.num)
# switch
doors.remove(selection)
selection = doors[0]
if selection != winner: #Change is done in this line
s()
#print("Switching win count: ",s.num)
for q in range (0,d):
a()
#print("Switching win count: ",s.num)
print("Switching percent: ",(s.num/d)*100)
#print("Not switching win count: ",b.num)
print("Not switching percent: ",(b.num/d)*100)
推荐阅读
- r - 训练集和测试集具有不同长度的唯一目标标签
- amazon-web-services - “http 通过 esp8266 发布到亚马逊网络服务器
- c# - 一个请求与 net core 3.0 中两个 Web API 的太多端点匹配
- sql-server - 主键范围取决于 SQL Server 中的行类型
- javascript - 二维数组javascript中的无限递归框
- c# - 如何强制 Unity 的 SerializedProperty 调用 OnValidate 回调?
- angular - 如何在Angular中垂直排列表格标题
- php - Laravel Eloquent,我如何从结果集的中间开始列出数据?
- oracle - 在 PL/SQL 中使用分析索引 [INDEX] 验证结构
- c++ - 在 pi 上使用 RPLIDAR A2 在 catkin_make 命令上出现错误 HectorSLAM