假设你站在'A‘的位置,而你的目的地是'B’(直线)。你的车的油箱可以容纳'L‘公里/英里的燃油。有'A‘和'B’两种方式的'n‘加油站,其中'A’是第一个加油站,'B‘是最后一个加油站。您将获得油箱容量'L',加油站列表'x‘和列表长度'n’。同样,'A‘(起始位置)是'n’的第一个索引,'B‘(目的地)是'n’的最后一个位置。你必须回答在到达'B‘之前你必须完成的最小续航次数(你的油箱在’A‘时是满的)。列表中的每个数字'x‘即。xi是一个离'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))但我不明白为什么它会显示超出范围的列表索引。如果有人收到并回答了这个问题,那么非常感谢。
发布于 2021-03-04 22:24:53
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))发布于 2021-03-04 22:34:30
因此,如果当前填充== 6,则传递第一个while条件(while currentrefill<=n)。
然后在第二个while中,您首先测试(currentrefill
您可以通过将
发布于 2021-03-04 22:55:50
在python列表中,索引从0开始。因此,第一个元素是x[0],第二个是x[1],依此类推,因此列表中的最后一个元素具有索引len(x) -1,因此x[n]是越界的。
在你的代码中,你可以写while currentrefill<=n:,lastrefill = currentrefill,x[lastrefill],这会导致x[n],因为<=n = currentrefill,这就是错误的来源。
为了解决这个问题,您可以将while currentrefill<=n:更改为while currentrefill<n:,将while (currentrefill<n)更改为while (currentrefill<n)
https://stackoverflow.com/questions/66476695
复制相似问题