【发布时间】:2017-06-13 03:24:26
【问题描述】:
我刚开始学习 python,我想看看我是否可以制作一个 python 版本的 monty hall 问题。当我使用 1 或 2 次迭代时,一切似乎都在小范围内工作,但过去没有任何工作。 for 循环没有完成我想要的迭代次数。
import random
def problem(tests):
wins = 0
losses = 0
doors = ["goat", "car", "goat"]
for test in range(tests):
#we shuffle the doors
random.shuffle(doors)
#the player picks a door
choice = random.choice(doors)
#monty chooses a door
montychoice = random.choice(doors)
while montychoice != 'car' or montychoice == choice:
montychoice = random.choice(doors)
#if the player's door is a car, he losses
if choice == 'car':
losses += 1
print 'goat'
elif choice == 'goat':
wins += 1
print 'car'
print "Switching wins: %d" % wins
print "Switching loses: %d" % losses
problem(100)
【问题讨论】:
-
尝试在您的 while 循环中添加打印语句。它是我看到的唯一阻塞代码。因此,如果由于某种原因没有满足您的退出条件,它将永远停留在 while 循环中。
-
您不想为此使用 random.choice() 。对于这个问题,知道选择了哪些门非常重要,而不仅仅是门后是什么,所以使用 random.randint(0, 2) 或 random.randrange(len(doors)) 来获取实际的门索引。