Search code examples
pythonalgorithmloopsnested-loopsindex-error

IndexError: list index out of range stair algorithm


I want to make an algorithm that counts how many stairs can guy jump from each stair. b is his jump height and c is height of each stair.

b = 7
c = [1, 2, 3, 4, 5, 4, 3, 2, 1]
indx = 1
indx1 = 1

for x in c:
    while x < b:
        if x + c[indx] < b:
            x = x + c[indx]
            indx += 1
            print(x)
        else:
            indx1 += 1
            indx = indx1

This code gives me this output: 3 Traceback (most recent call last): 6 File "file location*", line 9, in if x + c[indx] < b: IndexError: list index out of range

I don't know why it doesn't skip that if and doesn't go to the else statement...


Solution

  • I think you need make variable to hold threshold checker loop like this code:

    if __name__ == "__main__":
    
      b = 7
      c = [1, 2, 3, 4, 5, 4, 3, 2, 1]
      indx = 0
      indx1 = 0
    
      stop = 0
    
      for x in c:
        while stop < b:
           result = x + c[indx]
           print("check jump {}".format(result))
    
           if result < b:
             x = result
             indx += 1
             print("jump {}".format(x))
    
           else:
             indx1 += 1
             indx = indx1
             print("not jump {}".format(indx))
    
           stop = stop + indx
    

    I put a variable result is value after compute loop index for in. I hope that it would help you