我刚开始学习Python和我想的乐趣,看看我是否可以使蒙提霍尔问题的Python版本。当我使用1或2次迭代时,似乎一切都在小规模工作,但过去没有任何工作。 for循环没有完成我想要的迭代量。的Python没有完成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循环中。 – reticentroot
你不想为此使用random.choice()。对于这个问题,知道选择了哪些门非常重要,而不仅仅是门后面是什么,所以使用random.randint(0,2)或random.randrange(len(门))来获得实际的门指数。 – Cuagau