IndexError: list index out of range stair algorithm

IndexError: list index out of range stair algorithm

我想做一个算法来计算一个人可以从每个楼梯跳多少楼梯。 b是他的跳跃高度,c是每级楼梯的高度。

b = 7
c = [1, 2, 3, 4, 5, 4, 3, 2, 1]
indx = 1
indx1 = 1

for x in c:
    while x < b:
        if x + c[indx] < b:
            x = x + c[indx]
            indx += 1
            print(x)
        else:
            indx1 += 1
            indx = indx1

这段代码给出了这样的输出: 3个 追溯(最近一次通话): 6个 文件 "file location*",第 9 行,位于 如果 x + c[indx] < b: IndexError: 列表索引超出范围

我不知道为什么它不跳过 if 并且不转到 else 语句...

它正在崩溃,因为您的 while 循环正在检查是否 x < b。 b 是 7,而 c 中的所有内容都小于 7,因此它检查整个数组。 indx 从 1(而不是 0)开始并在每次循环时递增,因此在最后一个元素上它比数组中的最大索引大一个,并且您会得到您所看到的错误。

您需要执行以下操作之一:

  • 更改 while 循环的循环保护,使其在运行完数组之前停止
  • 在那个 if 语句 运行 之前检查 indx 是否太大了
  • indx 开始,值为 0,而不是 1
  • 当使用它作为列表的索引时,减去一个indx

任你选。

我认为您需要像下面的代码一样创建变量来保存阈值检查器循环:

if __name__ == "__main__":

  b = 7
  c = [1, 2, 3, 4, 5, 4, 3, 2, 1]
  indx = 0
  indx1 = 0

  stop = 0

  for x in c:
    while stop < b:
       result = x + c[indx]
       print("check jump {}".format(result))

       if result < b:
         x = result
         indx += 1
         print("jump {}".format(x))

       else:
         indx1 += 1
         indx = indx1
         print("not jump {}".format(indx))

       stop = stop + indx

我把一个变量result is value after compute loop index for in.希望对你有帮助