프로그래머스/level 2
[프로그래머스] 교점에 별 만들기
binaryJournalist
2022. 3. 3. 00:49
반응형
출처: 프로그래머스 코딩 테스트 연습, https://programmers.co.kr/learn/challenges
** Python
하는 중...!
교점까지는 접근해봤음..!
def solution(line):
visited = []
crossed = set()
answer = []
for i, l1 in enumerate(line):
for j, l2 in enumerate(line):
if (i, j) in visited or (j, i) in visited:
continue
a, b, e = l1
c, d, f = l2
if a*d - b*c != 0:
x = round((b*f - e*d)/(a*d - b*c), 2)
y = round((e*c - a*f)/(a*d - b*c), 2)
if x.is_integer() and y.is_integer(): crossed.add((x, y))
print(crossed)
if len(crossed) == 1: return ["*"]
return answer
x.is_integer() 랑 y.is_integer 에서 문제가 있었던 것 같다.
x == int(x)
y == int(y)로 바꾸니까 됐음
def solution(line):
visited = []
crossed = set()
answer = []
for i, l1 in enumerate(line):
for j, l2 in enumerate(line):
if (i, j) in visited or (j, i) in visited:
continue
a, b, e = l1
c, d, f = l2
if a * d - b * c != 0:
x = (b*f - e*d)/(a*d - b*c)
y = (e*c - a*f)/(a*d - b*c)
if x == int(x) and y == int(y):
crossed.add((int(x), int(y)))
xs = [c[0] for c in crossed]
x_min = min(xs)
x_max = max(xs)
ys = [c[1] for c in crossed]
y_min = min(ys)
y_max = max(ys)
answer = ['.' * (x_max - x_min + 1)] * (y_max - y_min + 1)
for c in crossed:
x, y = c
answer[y_max - y] = answer[y_max - y][:x - x_min] + '*' + answer[y_max - y][x - x_min + 1:]
return [''.join(ans) for ans in answer]
참고했던 식
from itertools import combinations
# 두 직선의 모든 좌표가 정수인 교점 구하기
def intersection_point(line1, line2):
a,b,e = line1
c,d,f = line2
if a*d == b*c:
return None
x = (b*f-e*d)/(a*d-b*c)
y = (e*c-a*f)/(a*d-b*c)
if x == int(x) and y == int(y):
return (int(x),int(y))
def solution(line):
N = len(line)
# 두 직선씩 짝지어 교점 구하기
combs = list(combinations(line,2))
points = set()
for comb in combs:
point = intersection_point(comb[0], comb[1])
if point:
points.add(point)
# 교점의 x좌표들
xs = [p[0] for p in points]
x_min = min(xs)
x_max = max(xs)
# 교점의 y좌표들
ys = [p[1] for p in points]
y_min = min(ys)
y_max = max(ys)
# 모두 . 으로 초기화
answer = ['.' * (x_max-x_min+1)] * (y_max-y_min+1)
# 각 좌표마다 * 그리기
for point in points:
x,y = point
answer[y_max-y] = answer[y_max-y][:x-x_min] + '*' + answer[y_max-y][x-x_min+1:]
return [''.join(ans) for ans in answer]
반응형