Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

โปรแกรมตรวจสอบจุดเป็นเส้นตรงหรือไม่ใน Python

สมมติว่ามีรายการพิกัด coordinates ในระนาบ Cartesian ต้องการตรวจสอบว่าจุดเหล่านี้อยู่บนเส้นตรงเดียวกันหรือไม่

ตัวอย่าง: coordinates = [[5,5],[8,8],[9,9]] ผลลัพธ์ True ความชัน 1

ขั้นตอนการแก้ปัญหา

  1. (x0, y0) = coordinates[0], (x1, y1) = coordinates[1]
  2. วน i จาก 2 ถึง len(coordinates)-1:
    • (x, y) = coordinates[i]
    • ถ้า (x0-x1)*(y1-y) != (x1-x)*(y0-y1): คืน False (ใช้ cross product หลีกเลี่ยงหารศูนย์)
  3. คืน 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