简体   繁体   中英

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

Consider you are standing at position 'A' and your destination is position 'B' (in a straight line). You car's fuel tank could hold fuel for 'L' km/miles. There are 'n' gas stations in the way of 'A' and 'B' including 'A' as the first gas station and 'B' as last gas station. You will be given with capacity of gas tank 'L', a list of gas station 'x' and the length of the list 'n'. Also 'A' (the starting position) is first index of 'n' and 'B' (the destination) is the last position of 'n'. You have to answer the minimum number of refill you have to do before getting to 'B' (your tank is full at 'A'). Every number in list 'x' ie. x[i] is a gas station distance from 'A'.

So I wrote this code.....

    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))

But I don't understand why it is showing list index out of range. If anyone gets it and answers it then thanks a lot.

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))

Here n=7. So if currentrefill == 6, you pass the first while condition (while currentrefill<=n)

Then in the second while, you first test (currentrefill<n) which also passes (currentfill is 6 and n is 7). You then try to test the right part. To do so you want to access x[currentrefill+1] which is x[7]. As indices in python start at 0, the last index of x is 6, which is why you have an out of range error.

You can convince yourself of this by replacing <n by <n-1 (You won't have an error in this case).

In python lists indexes start from 0. so the first element is x[0] , the second is x[1] etc, as a result the last element in the list has index len(x) -1 so x[n] is out of bounds.

in your code you write while currentrefill<=n: , lastrefill = currentrefill , x[lastrefill] this leads to x[n] since lastrefill = currentrefill <=n. thats where the error comes from.

in order to fix this you could change while currentrefill<=n: to while currentrefill<n: and while (currentrefill<n) to while (currentrefill<n)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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