【问题标题】:Python not finishing for loopPython没有完成for循环
【发布时间】: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)) 来获取实际的门索引。

标签: python for-loop iteration


【解决方案1】:

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

为了让您的 while 循环中断,montychoice 必须等于 car AND 玩家的选择。但是如果玩家选择的不是car,而是goat,那会怎样? while 循环永远不会中断。

我认为您的 while 循环需要 and 而不是 or。这样,如果任一条件不满足,循环就会中断。

【讨论】:

    【解决方案2】:

    问题是这个循环

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

    一旦玩家选择了汽车,这就是说无论蒙蒂选择汽车还是不选择汽车,他都必须选择另一个选择。所以他一直在挑选,而你的剧本没有任何进展。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-08-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-03
      • 1970-01-01
      • 2017-03-04
      相关资源
      最近更新 更多