알고리즘/프로그래머스
메뉴 리뉴얼
happenundo
2024. 6. 13. 14:34
728x90
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
dictionary를 사용해서 풀었다.
내 풀이
from itertools import combinations
def solution(orders, course):
answer = []
order_dict = dict()
candidate_set = set()
# 1단계: candidate_set 집합에 가능한 코스요리 메뉴 구성을 저장
for order in orders:
for cnt in course:
cur_order_list = list(combinations(list(sorted(order)), cnt))
for cur_order in cur_order_list:
candidate_set.add("".join(cur_order))
# 2단계: 만약, orders 안 원소에 candidate_set의 모든 원소가 있다면 order_dict에 추가한다.
for order in orders:
for cand in candidate_set:
is_in = all(c in order for c in cand)
if is_in:
if cand in order_dict.keys():
order_dict[cand] += 1
else:
order_dict[cand] = 1
# 3단계: answer_dict는 key가 위 order_dict의 key의 길이고, value는 그 중 가장 많이 주문된 course이다.
answer_dict = dict()
for order in order_dict.keys():
order_length = len(order)
if order_length not in answer_dict.keys():
if order_dict[order] >= 2:
answer_dict[order_length] = [order]
else:
# 만약 answer_dict에 이미 해당 길이의 가장 많이 주문된 course가 존재한다면, order_dict에서 주문된 횟수를 비교해 같을 경우 리스트에 추가
if order_dict[order] == order_dict[answer_dict[order_length][0]]:
answer_dict[order_length].append(order)
# 더 클경우에는 값을 바꿔줌
elif order_dict[order] > order_dict[answer_dict[order_length][0]]:
answer_dict[order_length] = [order]
# 4단계: answer에 answer_dict의 value들을 더해준다.
for ans in answer_dict.values():
answer += ans
# 5단계: 알파벳 오름차순으로 정렬해서 리턴
return sorted(answer)
풀면서 이게 맞나 싶었지만 어쨋든 패스는 했으니ㅎㅎ
더 효율적인 풀이
import collections
import itertools
def solution(orders, course):
result = []
for course_size in course:
order_combinations = []
for order in orders:
order_combinations += itertools.combinations(sorted(order), course_size)
most_ordered = collections.Counter(order_combinations).most_common()
result += [ k for k, v in most_ordered if v > 1 and v == most_ordered[0][1] ]
return [ ''.join(v) for v in sorted(result) ]
다른 사람 풀이에서 훨씬 효율적인 방법을 찾았다.
course_size별로 combination을 통해 가능한 course 조합을 찾은 후에 Counter 모듈의 most_common 함수를 사용해서 가장 많이 나온 course와 나온 개수를 찾는다.
그 후에 result에 나온 개수가 1보다 크고, 가장 많이 나온 횟수와 같은 경우들이 모인 course 조합이 담긴 리스트를 result에 더해준다.
훨씬 간단하다.
어떻게 이런 생각을..
728x90