[Programmers] Level 2. 메뉴 리뉴얼

2022. 11. 15. 18:52·코딩테스트/Python
728x90
반응형

🔗 Problem Link

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr


❔Thinking

  • 사람들이 가장 많이 주문한(2명 이상) 단품메뉴(단품 2개 이상)를 조합해 새로운 코스메뉴를 반환한다.
  • 코스를 구성하는 단품 메뉴의 수가 가장 많은 메뉴만을 코스로 구성한다. ("AB" 4개, "AC" 2개일 경우 "AB"만 해당)

💻Solution

1. key를 통한 정렬 풀이

from itertools import combinations
from collections import Counter
def solution(orders, course):
    answer = Counter()
    for menu in orders:
        menu = sorted(menu)
        for i in course:
            if i > len(menu):
                break
            for j in combinations(menu, i):
                if len(''.join(j)) >= 2:
                    answer[''.join(j)] += 1

    answer = sorted(answer.items(), key=lambda x: (len(x[0]), x[1]), reverse=True)
    temp = [menu for menu in answer if menu[1] >= 2]

    if len(temp) < 1:
        return []
    result = [temp[0][0]]
    max_len = temp[0][1]

    for i in range(1,len(temp)):
        if len(temp[i][0]) == len(temp[i-1][0]):
            if temp[i][1] >= max_len:
                result.append(temp[i][0])
        elif temp[i][1] >= temp[i-1][1]:
            max_len = temp[i][1]
            result.append(temp[i][0])
    return sorted(result)

 

2. Counter most_common을 활용한 풀이 (출처 - programmers 다른 사람 풀이)

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()
        print('most_ordered: ', most_ordered)
        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) ]

🗝️keypoint

  1. Counter는 defaultdict와 유사하게, key가 없으면 새롭게 정의하고, KeyError 없이 0을 반환한다.
  2. Counter most_common을 활용하면, 개수에 관계없이(가장 많은 값이 여러개여도) 최빈값을 출력할 수 있다.
  3. course는 사람들이 주문한 단품메뉴 개수와 관계없이 주어진다.

'코딩테스트 > Python' 카테고리의 다른 글

[Programmers] Level 3. 징검다리 건너기  (0) 2022.11.26
[Programmers] Level 3. 디스크 컨트롤러  (0) 2022.11.17
[Programmers] Level 3. 보석 쇼핑  (0) 2022.11.13
[Programmers] Level 3. 불량 사용자  (0) 2022.11.11
[Baekjoon] 1463 - 1로 만들기  (0) 2022.11.01
'코딩테스트/Python' 카테고리의 다른 글
  • [Programmers] Level 3. 징검다리 건너기
  • [Programmers] Level 3. 디스크 컨트롤러
  • [Programmers] Level 3. 보석 쇼핑
  • [Programmers] Level 3. 불량 사용자
swwho
swwho
일상을 데이터화하다
  • swwho
    하루한장
    swwho
  • 전체
    오늘
    어제
    • 분류 전체보기 (188)
      • ML_DL (39)
        • MUJAKJUNG (무작정 시리즈) (18)
        • 딥러닝 공부하기 (21)
      • 데이터사이언스 (1)
        • EDA (1)
        • 데이터과학을 위한 통계 (0)
      • 데이터엔지니어링 (2)
      • 논문리뷰 (2)
        • Computer Vision (2)
      • Python 활용하기 (12)
      • 코딩테스트 (127)
        • Python (109)
        • MySQL (14)
      • Git (3)
      • MySQL 활용하기 (0)
      • 일상 이야기 (1)
  • 블로그 메뉴

    • 홈
    • 태그
  • 최근 글

  • 250x250
  • hELLO· Designed By정상우.v4.10.3
swwho
[Programmers] Level 2. 메뉴 리뉴얼
상단으로

티스토리툴바