Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Program to check whether list of points form a straight line or not in Python
Suppose we have a list of 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.
Algorithm
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
How It Works
The algorithm uses the cross product method to check collinearity. For three points to be collinear, the slope between any two pairs of points must be the same. Instead of calculating slopes directly (which can cause division by zero), we use cross multiplication: (x0 - x1) * (y1 - y) == (x1 - x) * (y0 - y1).
Example
Let us see the following implementation to get better understanding −
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))
True
Testing with Non-Collinear Points
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()
# Test with points that don't form a straight line
coordinates = [[1, 2], [2, 3], [3, 5]]
print(ob.solve(coordinates))
False
Simplified Function Approach
def check_straight_line(coordinates):
if len(coordinates) < 3:
return True
(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
# Test cases
print(check_straight_line([[1, 2], [2, 3], [3, 4]])) # True
print(check_straight_line([[1, 1], [2, 2], [3, 4]])) # False
True False
Conclusion
The cross product method efficiently checks if points are collinear by avoiding division and handling vertical lines. This algorithm has O(n) time complexity and works reliably for all coordinate configurations.
