알고리즘/프로그래머스
2021 KAKAO BLIND RECRUITMENT 메뉴 리뉴얼
글을 쓰는 개발자
2021. 2. 1. 21:19
반응형
문제: programmers.co.kr/learn/courses/30/lessons/72411
코딩테스트 연습 - 메뉴 리뉴얼
레스토랑을 운영하던 스카피는 코로나19로 인한 불경기를 극복하고자 메뉴를 새로 구성하려고 고민하고 있습니다. 기존에는 단품으로만 제공하던 메뉴를 조합해서 코스요리 형태로 재구성해서
programmers.co.kr
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
import itertools
def solution(orders, course):
answer = []
for c in course:
dic={}
tmp=[]
Max=0
for ords in orders:
ords=list(ords)
ords.sort()
for val in itertools.combinations(ords,c):
dic[val]=dic.get(val,0)+1
Max=max(Max,dic[val])
for k,v in dic.items():
if v==Max and v!=1:
k=''.join(k)
tmp.append(k)
answer+=tmp
answer.sort()
return answer
|
cs |
1.itertools 중에서 combinations을 통하여 해당 알파벳으로 만들 수 있는 조합의 수를 만들고 나서 카운드를 한다.
2. value 중에서 최댓값이면서 1이 아닌 값들을 문자열로 변환한 다음에 리스트에 더한다.
3. 리스트를 정렬한다음에 반환하면 끝!!
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
import collections
import itertools
def solution2(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()
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) ]
|
cs |
이 코드는 프로그래머스에서 최상단에 있는 코드이다.
내 코드와 차이점이 있다면 collections.Counter 유무라 할 수 있겠다.
collections.Counter는 각 단어의 갯수들을 카운팅하여 사전형식으로 변환해주는 도구인데, 여기에서 most_common()이란 매서드는 데이터의 개수가 많은 순으로 배열을 리턴하는 매서드이다.
반응형