mercredi 24 juin 2020

Python If statement and While loop Bug with recursion

Hello I defined this small function with recursion:

def z_positions(frame,init_grid,f_count,_limit_):
    if f_count<_limit_:
        for i in range(np.shape(init_grid)[0]):
            for j in range(np.shape(init_grid)[0]):
                if init_grid[i,j]==1:
                    init_grid[i,j]=Z[f_count][i,j]
                else:
                    pass
        f_count+=1
        print(f_count<_limit_)
        new_grid=frame[f_count]
        z_positions(frame,new_grid,f_count,_limit_)
    else:
        print('end')
        return(frame)

So as you can see, the function calls itself only if the f_count is < than the _limit_, the frame parameter is only an np.array with more np.array inside with 1 and 0 values, and the parameter init_grid is only the first np.array of frame or better said frame[0].

What the function is doing is only replacing the values equal to 1 with some value from an identical np.array called Z that contains positions along the Z axis; however, even though f_count reaches the level of the _limit_ keeps executing the True portion of the if statement, which later returns me error as f_count surpassed the permited indexes as you can see here:

<ipython-input-49-0ac0d93e899c> in z_positions(frame, init_grid, f_count, _limit_)
 10         print(f_count<_limit_)
 11         new_grid=frame[f_count]
---> 12         z_positions(frame,new_grid,f_count,_limit_)
 13     else:
 14         print('end')

<ipython-input-49-0ac0d93e899c> in z_positions(frame, init_grid, f_count, _limit_)
  9         f_count+=1
 10         print(f_count<_limit_)
---> 11         new_grid=frame[f_count]
 12         z_positions(frame,new_grid,f_count,_limit_)
 13     else:

IndexError: list index out of range

I added the print(f_count<_limit_) to know what is happening and I can see that what I just said above is True because it prints False and it suppodsely should not do it as the print instruction should be excecuted only if the statement is True (same situation if I use while f_count<_limit_:). Could you please help me by pointing out what I am missing? Thanks! (Here a pic of the printting I just mentioned)

printing output

Aucun commentaire:

Enregistrer un commentaire