[Python] Python code for validating chess king movement

Discussão em 'Python' iniciado por Stack, Julho 8, 2025.

  1. Stack

    Stack Membro Participativo

    I am new to python and practising questions side by side. I came across a problem on snakify.org and solved using below code. Can this code be more simplified?

    Problem statement:

    Chess king moves horizontally, vertically or diagonally to any adjacent cell. Given two different cells of the chessboard, determine whether a king can go from the first cell to the second in one move. The program receives the input of four numbers from 1 to 8, each specifying the column and row number, first two - for the first cell, and then the last two - for the second cell. The program should output YES if a king can go from the first cell to the second in one move, or NO otherwise.

    I tried this solution on various possible sets and works fine but still, wonder if the lines of code could be reduced?

    x1 = int(input())
    y1 = int(input())
    x2 = int(input())
    y2 = int(input())
    def xcell(x1,x2):
    x=0
    if x1 -x2 > 0:
    x = x1 - x2
    elif x1-x2 < 0:
    x = x2-x1
    else: x
    return x
    def ycell(y1,y2):
    y=0
    if y1 -y2 >= 0:
    y = y1 - y2
    elif y1-y2 < 0:
    y = y2-y1
    else: y
    return y
    if ((xcell(x1,x2) == 1) & (ycell(y1,y2) == 0))or ((xcell(x1,x2) == 0)
    (ycell(y1,y2) == 1))or((xcell(x1,x2) == 1) & (ycell(y1,y2) == 1)):
    print("YES")
    else: print("NO")


    The expected output is YES if the user provides input 4,4,5,4

    Continue reading...

Compartilhe esta Página