我需要编写一个基于旧电视节目的python程序,让我们达成协议。我让程序打印出游戏的数量,以及用户是否应该切换或留下。现在我正试图找出如何打印用户应该停留和切换的百分比。在
测试输入如下:
25
7
exit
程序应输出的内容如下:
^{pr2}$以下是我的程序输出:
Enter Random Seed:
25
Welcome to Monty Hall Analysis
Enter 'exit' to quit
How many tests should we run?
7
Game 1
Doors: ['G', 'C', 'G']
Player Selects Door 1
Monty Selects Door 3
Player should switch to win.
Game 2
Doors: ['G', 'C', 'G']
Player Selects Door 2
Monty Selects Door 1
Player should stay to win.
Game 3
Doors: ['C', 'G', 'G']
Player Selects Door 1
Monty Selects Door 3
Player should stay to win.
Game 4
Doors: ['G', 'G', 'C']
Player Selects Door 3
Monty Selects Door 2
Player should stay to win.
Game 5
Doors: ['G', 'G', 'C']
Player Selects Door 3
Monty Selects Door 2
Player should stay to win.
Game 6
Doors: ['G', 'C', 'G']
Player Selects Door 3
Monty Selects Door 1
Player should switch to win.
Game 7
Doors: ['C', 'G', 'G']
Player Selects Door 2
Monty Selects Door 3
Player should switch to win.
How many tests should we run?
这是我做的代码:
import random
import sys
try:
randSeed = int(input('Enter Random Seed:\n'))
random.seed(randSeed)
except ValueError:
sys.exit("Seed is not a number!")
print('Welcome to Monty Hall Analysis')
print("Enter 'exit' to quit")
while True:
testNum = input('How many tests should we run?\n')
valid = False
while not valid:
try:
if testNum == "exit":
sys.exit("Thank you for using this program.")
else:
testNum = int(testNum)
valid = True
except ValueError:
testNum = input('Please enter a number:\n')
pStay = 0
pChange = 0
numGame = 0
for numGame in range(1, testNum + 1):
doorList = ['C', 'G', 'G']
random.shuffle(doorList)
print('Game', numGame)
print('Doors:', doorList)
playerDoor = random.randint(0,2)
montyDoor = random.randint(0,2)
print('Player Selects Door', playerDoor+1)
while montyDoor == playerDoor or doorList[montyDoor] == 'C':
montyDoor = random.randint(0,2)
print('Monty Selects Door', montyDoor+1)
if doorList[playerDoor] == 'C':
var = 0
else:
var = 1
if var == 0:
pStay += 1
print('Player should stay to win.')
pStay += 1
if var == 1:
print('Player should switch to win.')
抱歉,如果我的代码看起来不正确或令人困惑。这是我第一次编程谢谢。在
下面是Python3.6对使用集合进行交易的通用版本的模拟。在makea Deal的广义版本中,门和要打开的门的数量是不同的。参考:
https://math.stackexchange.com/questions/608957/monty-hall-problem-extended
如果在doors=3和doors U to_open=1的情况下运行,如果不选择切换门,则预期结果为33%,而在切换门时,预期结果为66%。在
好吧,你要记录下球员应该留下来赢得比赛的次数。所以停留百分比就是“(pStay/float(testNum))*100”,然后简单地从100中减去这个数字,得到要更改的百分比(因为它们必须加起来达到100%)
我想我应该提供更多的信息。这个公式是把停留游戏的数量从游戏总数中去掉。乘以100可以将十进制值转换为百分比。在
所以,如果你在1场比赛中,你打了10场比赛,那就是1/10,也就是0.1乘以100,就是10%。在
既然1/10你应该留下来,那就意味着9/10你应该改变。所以你可以减去停留百分比得到变化百分比,即100%-10%=90%
我把float()转换放在代码中的原因是,在python2中,如果将整数除以整数,它不会计算小数部分。它只是向下舍入到整数值。所以1/10等于0,不是1。在python3中,它确实产生了一个分数值,但是由于我不知道您使用的是哪个版本,所以可以安全地将其转换为float以获得预期的结果
看到下面添加的评论,你很接近。但是您缺少pSwitch的sum count变量。希望这有帮助。在
相关问题 更多 >
编程相关推荐