我刚刚开始学习 python,我想看看是否可以制作 monty Hall 问题的 python 版本。当我使用 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)
最佳答案
问题不在于 for 循环,而在于 while 循环。
为了让 while 循环中断,montychoice
必须等于 car
AND 玩家的选择。但是,如果玩家的选择不是汽车
,而是山羊
怎么办? while 循环永远不会中断。
我认为您的 while 循环需要 and
而不是 or
。这样,如果任一条件不满足,循环就会中断。
关于Python 未完成 for 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44511845/