https://programmers.co.kr/learn/courses/30/lessons/72411
from itertools import combinations
def solution(orders, course):
answer = []
menu_dict = {}
for order in orders:
for i in course:
candidates = list(combinations(order, i))
for can in candidates:
arr = sorted(list(can))
can = tuple(arr)
if can not in menu_dict:
menu_dict[can] = 1
else:
menu_dict[can] += 1
tmp = []
for key in menu_dict:
if menu_dict[key] == 1:
continue
tmp.append([key, menu_dict[key]])
for i in course:
max_val = 0
arr = [j for j in tmp if len(j[0]) == i]
arr_sorted = sorted(arr, key=lambda x: x[1], reverse=True)
if arr_sorted:
max_val = arr_sorted[0][1]
for item in arr_sorted:
if max_val == item[1]:
answer.append("".join(item[0]))
return sorted(answer)
메뉴 조합별 등장 횟수를 체크하기 위해 combinations, 딕셔너리를 사용했다.
우선 주문 하나당 만들어낼 수 있는 코스요리 조합을 combinations로 만든다.
해당 조합이 딕셔너리에 없다면 처음 등장했다는 뜻이므로 딕셔너리에 조합 : 1
을 추가해준다. 숫자 1은 1번 등장했다는 뜻이다.
해당 조합이 딕셔너리에 이미 들어있다면 조합 등장 횟수를 1 늘려준다.
모든 주문을 대상으로 이렇게 처리를 완료했다면 등장 횟수가 1인 것들을 제외한 조합들을 새 배열에 담아준다.
이제 메뉴 개수가 같은 조합들 중 최댓값을 구하고, 최댓값에 해당하는 메뉴 조합들만 추려내면 끝!