본문 바로가기

PS

프로그래머스 72411 Python [메뉴 리뉴얼]

from itertools import combinations
from collections import Counter

def solution(orders, course):
    answer = []
    for k in course:
        candidates = []  # 후보군 조합을 담는 리스트
        for order in orders:  # 각 문자열에 대하여
            order = sorted(order)  
            for c in combinations(order, k):  # 원소의 개수가 k개인 조합
                candidates.append(''.join(c))
        counts = Counter(candidates)  # 각 후보군의 등장 횟수 카운트
        if not counts: continue  # counts가 비어있는 경우 다음 k 진행
        max_count = max(counts.values())
        if max_count < 2: continue  # 최소 조건을 충족하지 못하는 경우 다음 k 진행
        for key, value in counts.items():
            if value == max_count:  # 등장 횟수가 최대 등장 횟수와 같은 경우
                answer.append(key)
    answer.sort()
    return answer