簡體   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