[알고리즘/파이썬] 코드잇 Brute Force 예제 - 가까운 매장 찾기

Song·2021년 7월 17일
0

알고리즘

목록 보기
18/22

문제 설명

튜플 리스트로 받은 좌표들이 있다. 두개의 좌표 위치끼리 비교해서 좌표 사이가 제일 짧은
좌표를 출력해라.

주제

  • Brute Force

난이도

  • 쉬움

1차 풀이

# 제곱근 사용을 위한 sqrt 함수
from math import sqrt

# 두 매장의 직선 거리를 계산해 주는 함수
def distance(store1, store2):
    return sqrt((store1[0] - store2[0]) ** 2 + (store1[1] - store2[1]) ** 2)

# 가장 가까운 두 매장을 찾아주는 함수
def closest_pair(coordinates):
    cur_distance = distance(coordinates[0], coordinates[1])
    for i in range(len(coordinates)):
        for j in range(len(coordinates)):
            if i != j and cur_distance > distance(coordinates[i], coordinates[j]):
                cur_distance = distance(coordinates[i], coordinates[j])
                result = []
                result.append(coordinates[i])
                result.append(coordinates[j])
        
    return result

test_coordinates = [(2, 3), (12, 30), (40, 50), (5, 1), (12, 10), (3, 4)]
print(closest_pair(test_coordinates))

풀이 방법

  1. 두개의 좌표 사이를 비교해서 제일 짧은 거리가 나온 좌표를 result 배열에 담은 후 반환.

2차 풀이

# 제곱근 사용을 위한 sqrt 함수
from math import sqrt

# 두 매장의 직선 거리를 계산해 주는 함수
def distance(store1, store2):
    return sqrt((store1[0] - store2[0]) ** 2 + (store1[1] - store2[1]) ** 2)

# 가장 가까운 두 매장을 찾아주는 함수
def closest_pair(coordinates):
    pair = [coordinates[0], coordinates[1]]
    for i in range(len(coordinates)):
        for j in range(len(coordinates)):
            store1, store2 = coordinates[i], coordinates[j] 
            if i != j and distance(pair[0], pair[1]) > distance(store1, store2):
                pair = [store1, store2]
                cur_distance = distance(store1, store2)
    return pair

test_coordinates = [(2, 3), (12, 30), (40, 50), (5, 1), (12, 10), (3, 4)]
print(closest_pair(test_coordinates))

풀이 방법

  1. 두개의 좌표 사이를 비교해서 제일 짧은 거리가 나온 좌표가 담긴 pair 배열 반환

문제를 풀고 알게된 개념 및 소감

1차 풀이와 2차 풀이안에서 사용된 로직에는 큰 차이가 없다,
다만 변수 사용에 앞서 1차 풀이때는 때려박는다는 느낌이 강했다면 2차 풀이는 좀 더 깔끔한 느낌.. 항상 간단한 코드를 짜더라도 한줄, 한줄 정성스럽게 하자.

profile
Learn From Yesterday, Live Today, Hope for Tomorrow

0개의 댓글