Python程序检查点列表是否构成直线
假设我们在笛卡尔平面上有一系列坐标,我们需要检查这些坐标是否构成一条直线段。
因此,如果输入类似于 coordinates = [(5, 5),(8, 8),(9, 9)],则输出将为 True,因为这些点构成一条斜率为 1 的线段。
为了解决这个问题,我们将遵循以下步骤 -
- (x0, y0) := coordinates[0]
- (x1, y1) := coordinates[1]
- 对于 i 从 2 到 coordinates 列表的大小 - 1,执行以下操作
- (x, y) := coordinates[i]
- 如果 (x0 - x1) * (y1 - y) 与 (x1 - x) * (y0 - y1) 不相同,则
- 返回 False
- 返回 True
让我们看看以下实现以获得更好的理解 -
示例
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))
输入
[[5, 5],[8, 8],[9, 9]]
Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career.
输出
True
广告