Reputation: 21
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
Upvotes: 0
Views: 9894
Reputation: 1
I am starting learning , I see it like this : `
x1=int(input("Введите значение x1: "))
y1=int(input("Введите значение y1: "))
x2=int(input("Введите значение x2: "))
y2=int(input("Введите значение y2: "))
if x1-1 == x2 or x1+1 == x2 and y1 +1 == y2 or y1-1 == y2:
print("Yes")
elif x1+1==y2-1 or x1+1==y2+1 and x1-1==y2-1 or x1-1==y2+1:
print("Yes")
else:
print("No")
`
Upvotes: 0
Reputation: 3038
You can use the abs
(absolute value) function to check the movement condition:
x1 = int(input())
y1 = int(input())
x2 = int(input())
y2 = int(input())
valid_move = abs(x1 - x2) <= 1 and abs(y1 - y2) <= 1 and (x1, y1) != (x2, y2)
print("YES" if valid_move else "NO")
Upvotes: 4