Level 2. 메뉴 리뉴얼

메뉴 리뉴얼

코딩테스트 연습 > 2021 KAKAO KAKAO BLIND RECRUITMENT > 메뉴 리뉴얼

https://programmers.co.kr/learn/courses/30/lessons/72411


문제 설명

# 문제 정리

- 입력: 순서가 없는 문자열로 구성된 리스트, 조합할 개수로 구성된 리스트
- 라이브러리: 문자열 조합을 위한 itertools.combinations, 조합된 문자열의 개수계산을 위한 collections.Counter
- 과정:
  1. 조합할 개수로 구성된 리스트에 맞추어 combinations를 이용
  2. combination된 값을 Counter을 이용해 개수 계산
  3. 조합된 것이 없거나, Counter의 최댓값이 1인 경우를 제외하고,
    ㄱ. Counter의 최댓값을 가지는 원소 리스트를 문자열로 변환 후 결과 array에 삽입

문제 풀이

# Input value
orders = ["ABCFG", "AC", "CDE", "ACDE", "BCFG", "ACDEH"]
course = [2,3,4]
# Set module
from itertools import combinations
from collections import Counter # dict subclass that count hashable

answer = []
for c in course:
    array = [] # local array
    for o in orders:
        array += combinations(sorted(o),c) # Using combinations to find case
        count = Counter(array)
    if len(count) != 0 and max(count.values()) != 1: # Ignore odict = 0 and max(odict) is 1
        answer += [''.join(x) for x in count if count[x] == max(count.values())] # Find max value of element list and ''.join() for str
sorted(answer)

전체 코드

from itertools import combinations
from collections import Counter
 
def solution(orders, course):
    answer = []
    for c in course: 
        array = []
        for o in orders:
            comb = combinations(sorted(o),c)
            array += comb
        odict = Counter(array)
        if len(odict) != 0 and max(odict.values()) != 1:
            answer += [''.join(c) for c in odict if odict[c] == max(odict.values())]

    return sorted(answer)

좋은 웹페이지 즐겨찾기