https://school.programmers.co.kr/learn/courses/30/lessons/72411
모범 답안
import collections
from itertools import combinations
def solution(orders, course):
result = []
for course_size in course:
order_combinations = []
for order in orders:
order_combinations += 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) ]
코스요리에 포함될 단품메뉴의 수를 기준으로 구성될 수 있는 모든 조합을 구한다. 이 조합들을 Counter하고 most_common()을 사용해 리스트 속 튜플 형태로 저장한다. 이후 most_ordered의 v값이 1 이상이고, most_ordered[0][1] == v , 즉 최빈값의 수와 같은 메뉴 조합일 때 result에 포함시켜 답을 구할 수 있다.
most_common() 함수 - 최빈값 구하기
collections.Counter(a).most_common(n) : a의 요소를 세어, 최빈값 n개를 반환합니다. (리스트에 담긴 튜플형태로)
예제 코드
import collections
a = [1,1,1,2,3,2,3,245,9]
print(collections.Counter(a).most_common(3))
출력 결과
>>>
[(1, 3), (2, 2), (3, 2)]
참조
https://infinitt.tistory.com/183
파이썬(Python) Collections 모듈 - counter , most_common
collections 모듈은 기본적으로 파이썬에 내장되어있는 내장함수입니다. (따로 설치가 필요 없..) 리스트나, 문자열의 요소에 대한 개수를 구할때 반복문으로도 구할 수 있지만, counter 함수를 사용
infinitt.tistory.com
'코딩테스트 > programmers (python)' 카테고리의 다른 글
Programmers / 3단계 / 기지국 설치 / python (0) | 2024.04.16 |
---|---|
Programmers / 2단계 / 전력망을 둘로 나누기 / python (0) | 2024.04.10 |
Programmers / 2단계 / 124 나라의 숫자 / python (0) | 2024.04.08 |
Programmers / 2단계 / 연속된 부분 수열의 합 / python (0) | 2024.04.06 |
Programmers / 2단계 / 큰 수 만들기 / python / 탐욕법(Greedy) (0) | 2024.04.04 |