Programmers를 통해 공개되어 있는 문제를 통해 알고리즘 역량을 향상시키고자 작성하고 있습니다.
알고리즘의 허점이나 더 간결한 아이디어가 있다면 언제든 지적해주세요.
- 문제 설명
문제 조건
문제에 대한 더 상세한 설명은 다음 URL을 통해 접속하면 알 수 있다.
https://programmers.co.kr/learn/courses/30/lessons/72411
본인은 Python을 통해 문제를 해결하였다.
from itertools import combinations
from collections import Counter
def solution(orders, course):
answer = []
for c in course:
tmp = []
for order in orders:
combi = combinations(sorted(order), c)
tmp += combi
counter = Counter(tmp)
if len(counter) != 0 and max(counter.values()) > 1:
answer += [''.join(f) for f in counter if counter[f] == max(counter.values())]
answer.sort()
return answer
이 문제는 조합(Combination)을 활용해서 푸는 것이 핵심이다.
라이브러리 사용
from itertools import combinations
from collections import Counter
combinations: 조합을 간편하게 사용할 수 있도록 Python에서 제공하는 라이브러리
Counter: 리스트 형태의 데이터 요소에 대해 각 요소 별, 동일한 것에 대해 카운트하고 이를 Dictionary 형태로 반환하는 라이브러리
.
.
tmp = []
for order in orders:
combi = combinations(sorted(order), c)
tmp += combi
counter = Counter(tmp)
.
.
combinations(list, n)
tmp += combi
counter = Counter(tmp)
.
.
if len(counter) != 0 and max(counter.values()) > 1:
answer += [''.join(f) for f in counter if counter[f] == max(counter.values())]
.
.
위 문제의 조건 중, 하나는 다음과 같다.
최소 2명 이상의 손님으로부터 주문된 단품메뉴 조합에 대해서만 코드요리 메뉴 후보에 포함하기로 했습니다.
위 조건을 만족하기 위한 if문이 다음과 같다.
if len(counter) != 0 and max(counter.values()) > 1
위 조건을 만족한다면 해당 조합을 join함수를 통해 answer 변수에 추가하는 작업을 진행한다.
위와 같이 작성 후, 채점을 하게 되면 다음과 같이 통과하는 것을 확인할 수 있다.
오늘은 combinations, Counter함수를 사용해보는 시간을 가져봤다.
아직 완벽히 이해하지 못한 부분도 존재하지만 이해만 정확히 한다면 유용하게 사용할 수 있는 라이브러리 함수인 것 같다.
더 다양한 예제를 통해 문제를 풀고 사용해봄으로써 확실히 이해하는 과정을 거쳐야겠다.
전체소스 git 링크
https://github.com/cho876/Algorithm/blob/master/Problem/Kakao/2021_kakao_blind_recruitment_q2.py