프로그래머스 - 메뉴 리뉴얼 python

Jamwon·2021년 8월 23일
0

알고리즘

목록 보기
15/18
post-thumbnail

문제링크

푸는 법

손님이 주문한 orders에서 만들수있는 모든 조합을 저장한다음에 중복되는 횟수를 count 한다.

제일 많이 나온 주문의 조합이 두번이상 시켜졌진것들중에 가많이 시켜졌다면 결과로 추가한다.

product permutations combinations

from itertools import product
from itertools import permutations
from itertools import combinations

파이썬 기본 라이브러리에서 제공하는 기능으로 파이썬에서 리스트에 있는 값들의 '모든' 조합을 구할수 있다.

  • 하나의 리스트에서 모든 조합을 계산할 때 - permutations combinations 사용
  • 두개 이상의 리스트에서 모든 조합을 계산할 때 - product 사용

permutations 순열

list(itertools.permutations(['1', '2', '3'], 2))

이 코드는 1,2,3 중에서 2개를 뽑는 모든 '순열'이다.
따라서 1,2 1,3 2,1 2,3 3,1 3,2
로 6개의 결과가 나오고

combinations 조합

list(itertools.combinations(['1', '2', '3'], 2))

이 코드는 1,2,3중에서 2개를 뽑는 '조합'을 구한다.

따라서 1,2 1,3 2,3 로 3개의 결과가 나온다.

product 중복 순열

product는 곱집합(Catesian product)을 구할때도 사용된다.

a = 'ABC'
b = 'XY'

print(itertools.product(a,b))

이 코드를 수행하면 'AX', 'BX' , 'CX', 'AV', 'BY', 'CY' 를 출력하게 된다.

Counter

collections의 모듈 Counter 클래스!

Counter 클래스는 파이썬의 기본 자료구조인 dictionary를 확장하고 있다.

기능으로는 iterable의 원소의 개수를 세어준다.
원소의 이름들은 dictionary의 key로 각각 원소의 갯수는 dictionary의 value로 저장된다.

또한 most_common()를 사용해서 가장 빈도수가 높은 key,value쌍부터 반환해준다.

코드

from itertools import combinations
from collections import Counter


def solution(orders, course):
    answer = []

    for n in course:
        array = []
        for o in orders:
            order = sorted(o)
            # print(list(combinations(order, n)))
            array.extend(list(combinations(order, n)))

        count = Counter(array).most_common()

        for index in range(len(count)):
            temp_max = count[0][1]
            if count[index][1] >= 2 and count[index][1] == temp_max:
                answer.append("".join(count[index][0]))
            else:
                break

    return sorted(answer)

위처럼 주문 받은 문자열을 정렬한다음에 course의 숫자 만큼 나올 경우의 수를 배열에 넣어준다.

그리고 Counter(array).most_common
를 사용해서 중복되는 횟수를 세어준다.

그리고 제일 많이나온 조합이 두번 이상이고 그중에서 max값을 answer에 추가해준다.

해결!

profile
한걸음씩 위로 자유롭게

0개의 댓글