Caleb Woods - 1 year ago 89

Python Question

I'm trying to create a simple game of "Jump It", it's supposed to take the numbers in a line (input obtained from an file), and find the cheapest route to get to the end. It takes the numbers in positions 1 & 2 and compares them to find which one is smaller, then adds that to the total "cost", then goes on to the next two.

So for the line 0 3 80 6 57 10, the cheapest route would be 3+6+10 for a total of 19. The current error I am getting is "index out of range", how would I fix this error?

`def shouldJump(A):`

cost = []

for line in A[0]:

if (A[1] > A[2]):

cost.append(A[1])

shouldJump(A[2:])

elif(A[1] < A[2]):

cost.append(A[2])

shouldJump(A[2:])

elif(A[0]==''):

shouldJump(A[1][1:])

print(cost, end='\n')

def main():

# This opens the file in read mode

filename = open('input.dat', 'r')

# Read in all the lines of the file into a list of lines

linesList = filename.readlines()

rows = [[int(n) for n in row.split()] for row in linesList]

myData = [[int(val) for val in line.split()] for line in linesList[1:]]

shouldJump(myData)

main()

Recommended for you: Get network issues from **WhatsUp Gold**. **Not end users.**

Answer Source

Here is a simple **recursive** code written in `Python 2.7`

. Have a look:

```
def shouldJump(A,i,n):
if i>n-1:
return 0
elif i+1>n-1:
return A[i]
else:
if A[i]<A[i+1]:
return A[i] + shouldJump(A,i+2,n)
else:
return A[i+1] + shouldJump(A,i+2,n)
A = [[0,3,80,6,57,10],[0,1,5,7,2]]
cost = []
for line in A:
cost.append(shouldJump(line,1,len(line)))
print cost
```

**Output:** `[19, 3]`

Hope it helps!!!

Recommended from our users: **Dynamic Network Monitoring from WhatsUp Gold from IPSwitch**. ** Free Download**