สมมติว่ามีรายการพิกัด coordinates ในระนาบ Cartesian ต้องการตรวจสอบว่าจุดเหล่านี้อยู่บนเส้นตรงเดียวกันหรือไม่
ตัวอย่าง: coordinates = [[5,5],[8,8],[9,9]] ผลลัพธ์ True ความชัน 1
ขั้นตอนการแก้ปัญหา
(x0, y0) = coordinates[0], (x1, y1) = coordinates[1]- วน
iจาก 2 ถึงlen(coordinates)-1:(x, y) = coordinates[i]- ถ้า
(x0-x1)*(y1-y) != (x1-x)*(y0-y1): คืนFalse(ใช้ cross product หลีกเลี่ยงหารศูนย์)
- คืน
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