본문 바로가기

Coding Test/Programmers

[프로그래머스/파이썬] 교점에 별 만들기

728x90

 

나의 풀이

from itertools import combinations

def intersection_point(one, two):
    A, B, C = one
    a, b, c = two
    m = a * B - A * b

    if not m:
        return False
    else:
        y = (A * c - a * C) / m
        x = -1 * (B * c - b * C) / m
    if y.is_integer() and x.is_integer():
        return (int(x), int(y))
    else:
        return False

def solution(line):
    start_x, start_y, end_x, end_y = 0, 0, 0, 0
    points = set()

    for c in combinations(line, 2):
        one, two = c
        result = intersection_point(one, two)
        if result:
            points.add(result)

    start_x = min(points, key=lambda x: x[0])[0]
    end_x = max(points, key=lambda x: x[0])[0]
    start_y = min(points, key=lambda x: x[1])[1]
    end_y = max(points, key=lambda x: x[1])[1]

    range_x = end_x - start_x + 1
    range_y = end_y - start_y + 1

    answer = [['.'] * range_x for i in range(range_y)]

    for point in points:
        x = point[0] - start_x
        y = end_y - point[1]
        answer[y][x] = '*'

    for i in range(range_y):
        answer[i] = ''.join(answer[i])

    return answer

 - 원래는 수식을 그대로 넣었는데, 부동소수점 문제인지 테스트가 다 틀리게 나왔다

 - 수식을 전개해 나누기를 최소화 했더니 해결.

 - itertools.chain.from_iterable 이 안돼서 그리는 부분이 조금 지저분하다. (chain이라도 쓸 걸 그랬다)

 

 

 

반응형