ye0nn
영차영차
ye0nn
전체 방문자
오늘
어제
  • 분류 전체보기 (61)
    • CS (0)
      • 운영체제 (0)
      • 네트워크 (0)
      • 알고리즘 & 자료구조 (0)
    • 코딩테스트 (48)
      • 프로그래머스 (40)
      • 백준 (8)
    • 프로그래밍 (11)
      • 프론트엔드 (3)
      • 자바스크립트 (0)
      • 스위프트 (7)
      • 파이썬 (1)
    • 취준기록 (1)

인기 글

블로그 메뉴

  • 홈
  • 태그
  • 방명록

티스토리

hELLO · Designed By 정상우.
ye0nn

영차영차

[프로그래머스] Level 2 - 메뉴 리뉴얼 (Python)
코딩테스트/프로그래머스

[프로그래머스] Level 2 - 메뉴 리뉴얼 (Python)

2022. 5. 13. 01:42

 

 

 

 

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

 

코딩테스트 연습 - 메뉴 리뉴얼

레스토랑을 운영하던 스카피는 코로나19로 인한 불경기를 극복하고자 메뉴를 새로 구성하려고 고민하고 있습니다. 기존에는 단품으로만 제공하던 메뉴를 조합해서 코스요리 형태로 재구성해서

programmers.co.kr

 

 

 

✅ Solution

  • combinations를 이용해 order 당 만들 수 있는 메뉴 조합을 모두 구한다.
  • 그 조합들을 defaultdict을 이용해 개수를 더해준다.
  • 그리고 각 course 당 가장 큰 값의 메뉴 조합을 넣어준다.

 

 

✅ Code

from itertools import combinations
from collections import defaultdict

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

    for order in orders:
        order = ''.join(sorted(list(order)))
        for course_size in course:
            if len(order) >= course_size:
                temp = list(combinations(order, course_size))
                for j in temp:
                    order_info[''.join(j)] += 1

    order_info = dict(sorted(order_info.items(), key=lambda x: -x[1]))

    for i in course:
        max_value = -1e9
        max_temp = []
        for key in order_info.keys():
            if len(key) == i and order_info[key] >= 2:
                if order_info[key] > max_value:
                    max_temp = [key]
                    max_value = order_info[key]
                elif order_info[key] == max_value:
                    max_temp.append(key)

        for i in max_temp:
            answer.append(i)

    answer.sort()
    return answer

 

 

 

✅ Solution

Counter 라이브러리를 활용한 좀 더 깔끔한 코드를 보고 다시 한번 작성했다. 

  • course_size 별로 combinations를 이용해 가능한 모든 조합을 구한 뒤, Counter로 개수를 세어준다.
  • 그리고 값 비교해서 answer에 넣어준다.

 

 

 

✅ Code

from itertools import combinations
from collections import Counter

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

    for course_size in course:
        order_combinations = []
        for order in orders:
            order_combinations += combinations(sorted(order), course_size)

        most_ordered = Counter(order_combinations).most_common()

        if len(most_ordered) == 0:
            continue

        max_value = most_ordered[0][1]

        for key, value in most_ordered:
            if value > 1 and value == max_value:
                answer.append(''.join(key))

    return sorted(answer)

 

 

 

 

소요 시간을 얼추 비슷비슷? 하다. 

 

 

📝 Today I Learned

counter

  • 해시 가능한 객체를 세기 위한 dict 서브 클래스
  • 요소가 딕셔너리 키로 저장되고 개수가 딕셔너리 값으로 저장되는 컬렉션이다.
  • most_common(n) 은 최빈값을 n개 반환해준다. 만약 n 이 생략되면 계수기 모든 요소를 반환한다.

 

 

 

https://docs.python.org/ko/3/library/collections.html#collections.Counter

'코딩테스트 > 프로그래머스' 카테고리의 다른 글

[프로그래머스] Level 2 - [1차] 캐시 (Python)  (0) 2022.05.17
[프로그래머스] Level 2 - [1차] 프렌즈4블록 (Python)  (0) 2022.05.17
[프로그래머스] Level 2 - 튜플 (Python)  (0) 2022.05.13
[프로그래머스] Level 2 - 후보키 (Python)  (0) 2022.05.13
[프로그래머스] Level 2 - 오픈채팅방 (Python)  (0) 2022.05.13
    '코딩테스트/프로그래머스' 카테고리의 다른 글
    • [프로그래머스] Level 2 - [1차] 프렌즈4블록 (Python)
    • [프로그래머스] Level 2 - 튜플 (Python)
    • [프로그래머스] Level 2 - 후보키 (Python)
    • [프로그래머스] Level 2 - 오픈채팅방 (Python)
    ye0nn
    ye0nn
    프론트엔드 개발자의 개발기록

    티스토리툴바