Program to check whether list of points form a straight line or not in Python

PythonServer Side ProgrammingProgramming

Suppose we have a list coordinates in a Cartesian plane, we have to check whether the coordinates form a straight line segment or not.

So, if the input is like coordinates = [(5, 5),(8, 8),(9, 9)], then the output will be True, as these points are forming a line segment with a slope 1.

To solve this, we will follow these steps −

  • (x0, y0) := coordinates[0]
  • (x1, y1) := coordinates[1]
  • for i in range 2 to size of coordinates list - 1, do
    • (x, y) := coordinates[i]
    • if (x0 - x1) * (y1 - y) is not same as (x1 - x) * (y0 - y1), then
      • return False
  • return True

Let us see the following implementation to get better understanding −

Example

 Live Demo

class Solution:
   def solve(self, coordinates):
      (x0, y0), (x1, y1) = coordinates[0], coordinates[1]
      for i in range(2, len(coordinates)):
         x, y = coordinates[i]
         if (x0 - x1) * (y1 - y) != (x1 - x) * (y0 - y1):
            return False
      return True
ob = Solution()
coordinates = [[5, 5],[8, 8],[9, 9]]
print(ob.solve(coordinates))

Input

[[5, 5],[8, 8],[9, 9]]

Output

True
raja
Published on 19-Nov-2020 11:25:20
Advertisements