繁体   English   中英

列表索引超出范围,但我不明白为什么

[英]List index out of range but I don't get why

假设您站在 position 'A' 并且您的目的地是 position 'B'(直线)。 您汽车的油箱可以容纳“L”公里/英里的燃料。 以“A”和“B”的方式有“n”个加油站,其中“A”作为第一个加油站,“B”作为最后一个加油站。 您将获得油箱容量“L”、加油站列表“x”和列表长度“n”。 此外,“A”(起始位置)是“n”的第一个索引,“B”(目标)是“n”的最后一个 position。 在到达“B”之前,您必须回答您必须完成的最少加注次数(您的油箱在“A”处已满)。 列表“x”中的每个数字,即。 x[i] 是距离“A”的加油站距离。

所以我写了这段代码......

    totalrefill, currentrefill = 0, 0
    while currentrefill<=n:
        lastrefill = currentrefill
        while (currentrefill<n) and (x[currentrefill+1]-x[lastrefill]<=L):
            currentrefill += 1
        if currentrefill==lastrefill:
            return "IMPOSSIBLE"
        if currentrefill<=n:
            totalrefill+=1

    return totalrefill

x = [0, 2, 3.5, 5, 7, 8.5, 9.5]
L = 4
n = len(x)

print(min_refuels(x,n,L))

但我不明白为什么它显示列表索引超出范围。 如果有人得到它并回答它,那么非常感谢。

def min_refuels(x, n, L):

    total_refill_count, refill_station, current_station = 0, 0, 0

    while current_station < n - 1:

        if x[current_station + 1] - x[refill_station] >= L:
            refill_station = current_station
            total_refill_count += 1

        current_station += 1

    return total_refill_count

x = [0, 2, 3.5, 5, 7, 8.5, 9.5]
L = 4
n = len(x)

print(min_refuels(x, n, L))

这里n=7。 因此,如果 currentrefill == 6,则通过第一个 while 条件(while currentrefill<=n)

然后在第二个时间里,您首先测试 (currentrefill<n),它也通过了(currentfill 为 6,n 为 7)。 然后,您尝试测试正确的部分。 为此,您需要访问 x[currentrefill+1],即 x[7]。 由于 python 中的索引从 0 开始,因此 x 的最后一个索引是 6,这就是您出现超出范围错误的原因。

您可以通过将 <n 替换为 <n-1 来说服自己相信这一点(在这种情况下您不会遇到错误)。

在 python 列表索引从 0 开始。所以第一个元素是x[0] ,第二个是x[1]等等,因此列表中的最后一个元素的索引是len(x) -1所以x[n]是出界。

在您编写的代码中, while currentrefill<=n:lastrefill = currentrefillx[lastrefill]这会导致x[n] ,因为 lastrefill = currentrefill <=n。 这就是错误的来源。

为了解决这个问题,您可以将while currentrefill<=n:更改为while currentrefill<n:while (currentrefill<n)更改为while (currentrefill<n)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM