관리 메뉴

솜씨좋은장씨

[leetCode] 1232. Check If It Is a Straight Line (Python) 본문

Programming/코딩 1일 1문제

[leetCode] 1232. Check If It Is a Straight Line (Python)

솜씨좋은장씨 2021. 2. 1. 20:46
728x90
반응형

You are given an array coordinates, coordinates[i] = [x, y], where [x, y] represents the coordinate of a point. Check if these points make a straight line in the XY plane.

 

 

Example 1:

Input: coordinates = [[1,2],[2,3],[3,4],[4,5],[5,6],[6,7]]
Output: true

Example 2:

Input: coordinates = [[1,1],[2,2],[3,4],[4,5],[5,6],[7,7]]
Output: false

Constraints:

  • 2 <= coordinates.length <= 1000
  • coordinates[i].length == 2
  • -10^4 <= coordinates[i][0], coordinates[i][1] <= 10^4
  • coordinates contains no duplicate point.

Solution

class Solution:    
    def checkStraightLine(self, coordinates: List[List[int]]) -> bool:
        x_points = [x[0] for x in coordinates]
        
        if len(set(x_points)) == 1:
            return True
        else:
            point1_x, point1_y = coordinates[0]
            point2_x, point2_y = coordinates[1]
            dy = (point1_y-point2_y)
            dx = (point1_x-point2_x)
            if dx == 0:
                dx = 1

            bias = point1_y - dy/dx * point1_x

            for i in range(2,len(coordinates)):
                point_x, point_y = coordinates[i]
                if point_y != dy/dx* point_x + bias:
                    return False
        return True

 

SOMJANG/CODINGTEST_PRACTICE

1일 1문제 since 2020.02.07. Contribute to SOMJANG/CODINGTEST_PRACTICE development by creating an account on GitHub.

github.com

Comments