【问题标题】:Infinite loop in pythonpython中的无限循环
【发布时间】:2013-10-12 19:17:56
【问题描述】:

我应该为以下问题编写代码:

玩家掷出两个六面骰子。如果两个骰子的和不是 七、总和加上玩家的总分和玩家 再次滚动。当玩家掷出七的总和时,游戏是 结束了。

这是我目前所拥有的:

def main():
  dice1 = randrange(1, 7,)
  dice2 = randrange(1, 7,)

  roll = dice1 + dice2
  score = 0
  count = 0
  while roll != 7:
    count = count + 1
    score = score + roll
    if roll == 7:
     break
  print count
  print score

main()

但是,当它应该滚动骰子时,它只会给我一个无限循环,直到骰子的总和为 7。

我该如何解决?

【问题讨论】:

  • 您不会在 while 循环中更改 roll 的值。难怪它会陷入无限循环
  • 另外,你不需要if roll == 7: breakwhile roll != 7: 处理
  • print ( (lambda f: f (f, 0, 0, 0, __import__ ('random') ) ) (lambda f, r, c, s, i: (c, s) if r == 7 else f (f, i.randint (1, 6) + i.randint (1, 6), c + 1, s + r, i) ) )

标签: python while-loop infinite-loop


【解决方案1】:

你没有更新roll;确保你在循环中再次滚动:

roll = randrange(1, 7) + randrange(1, 7)
score = count = 0

while roll != 7:
    score += roll
    count += 1
    # re-roll the dice for the next round
    roll = randrange(1, 7) + randrange(1, 7)

dice1 + dice2 分配给roll 后,它本身不会在每次循环后“重新掷骰子”。

【讨论】:

  • 我将roll=0 设置在顶部只是为了将所有滚动的逻辑保持在一个位置(在循环结束时)。这是一个额外的循环,但在性能方面并不昂贵。
  • 当然可以,但是您还必须将count 设置为-1
【解决方案2】:

您需要在每次迭代时更新roll 的值。现在,roll 永远不会改变,所以它永远不会等于 7(这意味着循环将永远运行)。

我想你希望你的代码是这样的:

from random import randrange
def main():

  # Note that the following two lines can actually be made one by doing:
  # score = count = 0
  score = 0
  count = 0

  # There is really no need to define dice1 and dice2
  roll = randrange(1, 7,) + randrange(1, 7,)

  # This takes care of exiting the loop when roll = 7
  # There is no need for that if block
  while roll != 7:

    # Note that this is the same as count = count + 1
    count += 1

    # And this is the same as score = score + roll
    score += roll

    # Update the value of roll
    # This is actually the line that fixes your problem
    roll = randrange(1, 7,) + randrange(1, 7,)

  print count
  print score

main()

另外,请注意我对脚本进行了一些更改以提高效率。

【讨论】:

    【解决方案3】:

    您必须在while 循环中获得新的骰子数

    def main():
          dice1 = randrange(1, 7,)
          dice2 = randrange(1, 7,)
    
          roll = dice1 + dice2
          score = 0
          count = 0
          while roll != 7:
            count = count + 1
            score = score + roll
            if roll == 7:
              break
            dice1 = randrange(1, 7,)
            dice2 = randrange(1, 7,)
            roll = dice1 + dice2
          print count    
          print score
    
    main()
    

    【讨论】:

      【解决方案4】:

      这里有一个优雅的解决方案:

      from random import randint
      
      count, score = 0, 0
      while True:
          roll = randint(1,6) + randint(1,6)
          if roll == 7:
              break
          count += 1
          score += roll
      
      print count, score
      

      【讨论】:

        猜你喜欢
        • 2017-10-13
        • 2012-08-28
        • 2017-10-12
        • 2020-11-30
        • 2015-05-22
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多