https://programmers.co.kr/learn/courses/30/lessons/72411
✅ 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 |