0

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()
DSM
  • 342,061
  • 65
  • 592
  • 494

3 Answers3

1

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

User_Targaryen
  • 4,125
  • 4
  • 30
  • 51
0

Here's a simple way of accomplishing this

cost = 0
for pair in izip_longest(fillvalue=max(A) + 1, *[iter(A)] * 2):
    cost += min(pair)

See the grouper recipe from https://docs.python.org/2/library/itertools.html#recipes

Anthony Oteri
  • 402
  • 4
  • 14
0

You can do this with a one-line list comprehension (not recursive; the requirement to use recursion was added afterwards, grumble grumble):

min_cost = sum(min(pair) for pair in zip(A[::2], A[1::2]))
16

and if you want the 'min_route':

min_route = [min(pair) for pair in zip(A[::2], A[1::2])]
[0, 6, 10]

where the 'pairs' idiom is taken from Pairs from single list

Community
  • 1
  • 1
smci
  • 32,567
  • 20
  • 113
  • 146