Program to check whether one point can be converted to another or not in Python

PythonServer Side ProgrammingProgramming

Suppose we have a starting points (sx, sy), and target point (tx, ty), we have to check whether a sequence of moves exists from the start point to the end point. Here move consists of taking a point (x, y) and transforming it to either (x, x+y) or (x+y, y).

So, if the input is like (sx, sy) = (1,1) (tx, ty) = (4,5), then the output will be True, this is because move (1,1) to (2,1), then (3,1), then (4,1), then (4,5).

To solve this, we will follow these steps −

  • Define a function solve() . This will take sx, sy, tx, ty

  • if sx > tx or sy > ty, then

    • return False

  • if sx is same as tx, then

    • return(ty-sy) mod sx is same as 0

  • if sy is same as ty, then

    • return(tx - sx) mod sy is same as 0

  • return solve(sx, sy, tx-ty, ty) or solve(sx, sy, tx, ty-tx)


Let us see the following implementation to get better understanding

def solve(sx, sy, tx, ty):
   if sx > tx or sy > ty:
      return False
   if sx == tx:
      return (ty-sy)%sx == 0
   if sy == ty:
      return (tx - sx)%sy == 0
   return solve(sx, sy, tx-ty, ty) or solve(sx, sy, tx, ty-tx)

(sx, sy) = (1,1)
(tx, ty) = (4,5)
print(solve(sx, sy, tx, ty))


(1,1), (4,5)


Published on 08-Oct-2021 07:26:55