2017-06-13 125 views
1

我刚开始学习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) 
+0

尝试增加打印语句在while循环。它是我看到的唯一的代码块。所以如果出于任何原因你的退出条件没有得到满足,它将永远留在while循环中。 – reticentroot

+0

你不想为此使用random.choice()。对于这个问题,知道选择了哪些门非常重要,而不仅仅是门后面是什么,所以使用random.randint(0,2)或random.randrange(len(门))来获得实际的门指数。 – Cuagau

回答

1

问题不在于for循环,而在于while循环。

为了让你的while循环中断,montychoice必须等于car和玩家的选择。但是,如果玩家的选择就是不car,但它的goat? while循环永远不会中断。

我想你想and,而不是or您while循环。这样,如果任何一个条件都不符合,循环就会中断。

+0

谢谢你解决了我的问题:) –

0

问题是这样的循环

while montychoice != 'car' or montychoice == choice: 
     montychoice = random.choice(doors) 

一旦玩家选择了汽车,这是说蒙蒂是否挑选汽车或没有汽车,他挑的另一种选择。所以他一直在不停地挑选,而且你不会在剧本中有更多的选择。