선물을 직접 전하기 힘들 때 카카오톡 선물하기 기능을 이용해 축하 선물을 보낼 수 있습니다. 당신의 친구들이 이번 달까지 선물을 주고받은 기록을 바탕으로 다음 달에 누가 선물을 많이 받을지 예측하려고 합니다.
친구들의 이름을 담은 1차원 문자열 배열 friends 이번 달까지 친구들이 주고받은 선물 기록을 담은 1차원 문자열 배열 gifts가 매개변수로 주어집니다. 이때, 다음달에 가장 많은 선물을 받는 친구가 받을 선물의 수를 return 하도록 solution 함수를 완성해 주세요.
구현 문제. 선물을 주고받은 것을 어떤 자료구조로 표현하냐? 가 주 고민 포인트였다.
처음에는 dictionary로 처리하려고 했는데(디버깅하기 편하게 라는 소소한 이유...) 매트릭스로 처리. 개중에서도 numpy array로 변환하여 사용했다.
np를 쓴 이유는 row / col 단위로 묶어 접근하기 용이해서이다. array를 썼다면 list comprehension을 썼을 것 같다.
from collections import defaultdict
import numpy as np
def solution(friends, gifts):
present_matrix = [[0 for _ in friends] for _ in friends]
for giver, reciever in [g_r.split() for g_r in gifts]:
giver_idx, reciever_idx = friends.index(giver), friends.index(reciever)
present_matrix[giver_idx][reciever_idx] += 1
present_matrix = np.array(present_matrix)
present_status = defaultdict(int)
ratios = [sum(present_matrix[a, :]) - sum(present_matrix[:, a]) for a in range(len(friends))]
for a, A in enumerate(friends):
for _b, B in enumerate(friends[a+1:]):
b = a + _b + 1
if present_matrix[a][b] == present_matrix[b][a]:
a_ratio = ratios[a]
b_ratio = ratios[b]
if a_ratio > b_ratio:
present_status[a] += 1
elif a_ratio < b_ratio:
present_status[b] += 1
elif present_matrix[a][b] > present_matrix[b][a]:
present_status[a] += 1
else:
present_status[b] += 1
answer = max(present_status.values()) if present_status else 0
# answer = 0
return answer