【问题标题】:Python - mystery infinite loopPython - 神秘的无限循环
【发布时间】:2013-09-16 11:10:56
【问题描述】:

I'm taking this Python course online 并试图弄清楚为什么当 x 值为 3 时这个循环是无限的

def mystery(x):
  a = [0, 4, 0, 3, 2]
  while x > 0:
    x = a[x]
  return "Done"

mystery(3) 无限运行。

是不是因为当列表值已经是 3 时它一直试图将 x 设置为 3?

【问题讨论】:

  • 你可能想要while x != a[x]: 而不是while x > 0: 。这将处理映射到自身的 both 值,而不仅仅是其中一个。但是,如果有任何循环,这仍然无济于事(例如,a = [1, 0, 2, 3, 4] 将在 01 上永远循环)。

标签: python indexing while-loop infinite-loop


【解决方案1】:

是的,x 总是 3。最初 x 是 3,并且在索引 3 处列表的值,即 a[x] 也是 3。因此无限循环。

【讨论】:

    【解决方案2】:
    def mystery(x):               # Here x = 3
      a = [0, 4, 0, 3, 2]         
      while x > 0:                # Since x = 3 the program enters the loop
        x = a[x]                  # a[3] = 3 and hence x is assigned 3. Again x = 3 and therefore 
                                  # the program will get into an infinite loop in the while 
                                  # statement.
      return "Done"
    

    【讨论】:

      【解决方案3】:

      请记住,列表索引从零开始,因此 a[3]=3。然后,尝试手动展开循环:

      1. x = 3

        是 x=3 > 0,是的

      2. x = a[x] = a[3] = 3

        是 x=3 > 0,是的

      3. x = a[x] = a[3] = 3

        是 x=3 > 0,是的

      等等。

      【讨论】:

        【解决方案4】:

        “是不是因为在列表值已经是3的情况下,它一直试图将x设置为3?”

        是的。 a[3] 指向该列表中的 3。所以x 只是被重复分配给3

        【讨论】:

          【解决方案5】:

          记住数组索引从0开始,所以如果

          a = [0, 4, 0, 3, 2]
          

          然后a[3] == 3

          所以这一行

          x = a[x] 
          

          永远不要将 x 设置为 3 以外的任何值!

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2014-10-23
            • 1970-01-01
            • 1970-01-01
            • 2014-06-07
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2022-01-18
            相关资源
            最近更新 更多