✅문제 설명
점 네 개의 좌표를 담은 이차원 배열 dots가 다음과 같이 매개변수로 주어집니다.
[[x1, y1], [x2, y2], [x3, y3], [x4, y4]]
주어진 네 개의 점을 두 개씩 이었을 때, 두 직선이 평행이 되는 경우가 있으면 1을 없으면 0을 return 하도록 solution 함수를 완성해보세요.✅제한사항
- dots의 길이 = 4
- dots의 원소는 [x, y] 형태이며 x, y는 정수입니다.
- 0 ≤ x, y ≤ 100
- 서로 다른 두개 이상의 점이 겹치는 경우는 없습니다.
- 두 직선이 겹치는 경우(일치하는 경우)에도 1을 return 해주세요.
- 임의의 두 점을 이은 직선이 x축 또는 y축과 평행한 경우는 주어지지 않습니다.
def solution(dots):
answer = 0
dots_idx = [[0, 1, 3, 2], [0, 2, 3, 1], [1, 2, 0, 3]]
for d1, d2, d3, d4 in dots_idx:
x1, y1 = dots[d1][0], dots[d1][1]
x2, y2= dots[d2][0], dots[d2][1]
x3, y3= dots[d3][0], dots[d3][1]
x4, y4= dots[d4][0], dots[d4][1]
if (y1-y2)*(x3-x4) == (y3-y4)*(x1-x2) :
answer = 1
return answer
from itertools import combinations
def solution(dots):
a = []
for (x1,y1),(x2,y2) in combinations(dots,2):
a.append((y2-y1,x2-x1))
for (x1,y1),(x2,y2) in combinations(a,2):
if x1*y2==x2*y1:
return 1
return 0
파이썬이 제공하는 라이브러리를 이용해 combination() 함수를 사용해서 풀이했다.
def solution(dots):
[[x1, y1], [x2, y2], [x3, y3], [x4, y4]]=dots
answer1 = ((y1-y2)*(x3-x4) == (y3-y4)*(x1-x2))
answer2 = ((y1-y3)*(x2-x4) == (y2-y4)*(x1-x3))
answer3 = ((y1-y4)*(x2-x3) == (y2-y3)*(x1-x4))
return 1 if answer1 or answer2 or answer3 else 0
좌표를 dots와 같은 형태의 배열로 만들어 바로 대입하고
만들 수 있는 조합을 모두 계산해야 풀이했다.
평행하다면 answer1,2,3에 담긴 값은 True 이므로,
return 1 if answer1 or answer2 or answer3 else 0
라고 한줄로 표현할 수 있다.
파이썬은 permutaion 순열과 combination 조합을 쓸 수 있는 라이브러리를 제공한다.
from itertools import combinations, permutations
nums = [1,2,3,4]
perm = list(permutations(nums, 2))
출력
[(1, 2), (1, 3), (1, 4), (2, 1), (2, 3), (2, 4), (3, 1), (3, 2), (3, 4), (4, 1), (4, 2), (4, 3)]
from itertools import combinations, permutations
nums = [1,2,3,4]
combi = list(combinations(nums, 2))
출력
[(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]