본문 바로가기

Python(알고리즘,문제풀이)/프로그래머스(입문100제)

코딩테스트입문 / 평행

728x90

📚문제

출처 : 프로그래머스 / 평행 (https://school.programmers.co.kr/learn/courses/30/lessons/120875)

 

📝풀이

def solution(dots):
    slope_list = []

    for idx in range(len(dots)-1):
        x1, y1 = dots[idx]
        x2, y2 = dots[idx+1]
        slope_list.append((y2-y1)/(x2-x1))


    for idx in range(1,len(dots)-1):
        x1, y1 = dots[idx]
        x2, y2 = dots[idx+1]
        slope_list.append((y2-y1)/(x2-x1))

    for idx in range(2,len(dots)-1):
        x1, y1 = dots[idx]
        x2, y2 = dots[idx+1]
        slope_list.append((y2-y1)/(x2-x1))

    for i in slope_list:
        if slope_list.count(i) == 4:
            return 1
            break
    return 0

몇시간 심혈을 기울여 풀었는데

88점

2가지 테스트케이스에서 틀렸다

 

그래서 slope_list의 개수가 4이상인경우도 포함시켜야 하나해서

그렇게 제출해봤는데 오히려 점수가 떨어졌다...'

 

계속 확인해봐도 답이 안 나올 것 같아서 

우선 보류해두고 구글링 하여 코드 참고

 

def slope(dot1,dot2):
    return (dot2[1] - dot1[1]) / (dot2[0] - dot1[0])

def solution(dots):
    answer = 0
    if slope(dots[0],dots[1]) == slope(dots[2],dots[3]):
        answer = 1
    elif slope(dots[0],dots[2]) == slope(dots[1],dots[3]):
        answer = 1
    elif slope(dots[0],dots[3]) == slope(dots[1],dots[2]):
        answer = 1
    return answer

 

1.

두 점의 기울기 구하는 식을 함수로 만들어주었다

한층 간결하고 직관적으로 보인다

 

2.

평행일 때 1을 return하고 아닐 때 0을 리턴하는 방법을

while문을 사용해야하나 생각했는데 

그냥 answer 나 result 변수에 0 할당 후

기울기가 일치할 경우(평행일 경우) 에만 1로 지정해주면 된다

 

728x90