用 Python 检查点列表是否形成直线的程序
pythonserver side programmingprogramming
假设我们在笛卡尔平面中有一个坐标列表,我们必须检查坐标是否形成直线段。
因此,如果输入为 coordinates = [(5, 5),(8, 8),(9, 9)],则输出将为 True,因为这些点形成了一个斜率为 1 的线段。
为了解决这个问题,我们将遵循以下步骤 −
- (x0, y0) := coordinates[0]
- (x1, y1) := coordinates[1]
- 对于范围为 2 到坐标列表大小 - 1 的 i,执行
- (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]]
输出
True
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

