0

This function uses recursion to find the easiest way for a knight to get from one place on the chess board to another the recursive function locate returns None. Please explain why

def knight(p1, p2):
    cord1 = [ord(p1[0])-97, int(p1[1])-1]
    cord2 = [ord(p2[0])-97, int(p2[1])-1]
    
    def locate(legal_moves, endpoint, counter):
        if endpoint in legal_moves:
            print(counter)
            return counter
        else:
            for move in legal_moves:
                semi_legal_moves = [
                [move[0]+2,move[1]+1], 
                [move[0]+1,move[1]+2], 
                [move[0]+2,move[1]-1], 
                [move[0]+1,move[1]-1], 
                [move[0]-1,move[1]+2], 
                [move[0]-2,move[1]+1], 
                [move[0]-1,move[1]-2],
                [move[0]-2,move[1]-1,]]
                legal_moves = legal_moves + [i for i in semi_legal_moves if i[0] >=0 and i[0] <8 and i[1] >=0 and i[1] <8]
            locate(legal_moves, endpoint, counter +1)
    return locate([cord1], cord2, 0)
print(knight('a1', 'c1'))

1 Answers1

0

You have implemented recursion in your function locate.

Thus, you should add return there too.

def locate(legal_moves, endpoint, counter):
        if endpoint in legal_moves:
            print(counter)
            return counter
        else:
            for move in legal_moves:
                semi_legal_moves = [
                [move[0]+2,move[1]+1], 
                [move[0]+1,move[1]+2], 
                [move[0]+2,move[1]-1], 
                [move[0]+1,move[1]-1], 
                [move[0]-1,move[1]+2], 
                [move[0]-2,move[1]+1], 
                [move[0]-1,move[1]-2],
                [move[0]-2,move[1]-1,]]
                legal_moves = legal_moves + [i for i in semi_legal_moves if i[0] >=0 and i[0] <8 and i[1] >=0 and i[1] <8]
            return locate(legal_moves, endpoint, counter +1)  # add return here
PaxPrz
  • 1,778
  • 1
  • 13
  • 29