Home > Software engineering >  Create a chess knight movement validator function, for the provided coordinations determine if knigh
Create a chess knight movement validator function, for the provided coordinations determine if knigh

Time:11-28

Create a chess knight movement validator function, for the provided coordination determine if knight can move this way or not I.e.

knight_validator(‘b1’, ‘a3’) -> True

knight_validator(‘b1’, ‘b3’) -> False

My code looks like this

def knight_validator(x1, x2, y1, y2):
 x1 = {'A': 1, 'B': 2, 'C': 3, 'D': 4, 'E': 5, 'F': 6, 'G': 7, 'H': 8}
 x2 = {'1', '2', '3', '4', '5', '6', '7', '8'} 
 y1 = {'A': 1, 'B': 2, 'C': 3, 'D': 4, 'E': 5, 'F': 6, 'G': 7, 'H': 8} 
 y2 = {'1', '2', '3', '4', '5', '6', '7', '8'}
 
dx = abs(x1- x2) 
dy = abs(y1 - y2) 

if abs(x1 - x2) == 2 and abs(y1 - y2) == 1 or abs(y1 - y2) == 2 and abs(x1 - x2) == 1: 
   print('True') 
else: 
   print('False')

knight_validator('B', '1', 'A', '3')

How to fix it?

CodePudding user response:

Check this:

def check_coord(a) -> bool:
    if isinstance(a, int):
        if 1 <= a <= 8:
            return True
    else:
        if ord("A") <= ord(a) <= ord("H"):
            return True
    return False


def knight_validator(x1, y1, x2, y2) -> bool:
    for a in (x1, y1, x2, y2):
        if not check_coord(a):
            return False
    if abs(ord(x1) - ord(x2)) == 1 and abs(y1 - y2) == 2:
        return True
    if abs(ord(x1) - ord(x2)) == 2 and abs(y1 - y2) == 1:
        return True
    return False


print(knight_validator("B", 1, "A", 3))
print(knight_validator("B", 1, "B", 3))
print(knight_validator("U", 5, "H", 10))

This solution also checks input data for correctness.

CodePudding user response:

Use this:

x1=0
x2=0
y1=0
y2=0
def knight_validator(x1, x2, y1, y2):
    x1 = {'A': 1, 'B': 2, 'C': 3, 'D': 4, 'E': 5, 'F': 6, 'G': 7, 'H': 8}
    x2 = {'1', '2', '3', '4', '5', '6', '7', '8'} 
    y1 = {'A': 1, 'B': 2, 'C': 3, 'D': 4, 'E': 5, 'F': 6, 'G': 7, 'H': 8} 
    y2 = {'1', '2', '3', '4', '5', '6', '7', '8'}

 
dx = abs(x1- x2) 
dy = abs(y1 - y2) 

if abs(x1 - x2) == 2 and abs(y1 - y2) == 1 or abs(y1 - y2) == 2 and abs(x1 - x2) == 1: 
   print('True') 
else: 
   print('False')

knight_validator('B', '1', 'A', '3')
  • Related