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]]
輸出
True
廣告