개발일기 [Python 파이썬]
[알고리즘] 최빈값 구하기
neullo
2024. 3. 29. 09:48
최빈값은 주어진 값 중에서 가장 자주 나오는 값을 의미합니다. 정수 배열 array가 매개변수로 주어질 때, 최빈값을 return 하도록 solution 함수를 완성해보세요. 최빈값이 여러 개면 -1을 return 합니다.
from collections import Counter
collections 모듈에서 Counter 클래스를 가져옵니다. 이 클래스는 주어진 시퀀스의 각 요소의 개수를 세는 데 사용됩니다.
def solution(array):
counts = {}
for num in array:
counts[num] = counts.get(num, 0) + 1
max_count = max(counts.values())
most_common = [num for num, count in counts.items() if count == max_count]
return most_common[0] if len(most_common) == 1 else -1
Counter 객체를 사용하여 배열의 요소를 세어 딕셔너리 형태로 반환합니다. Counter는 주어진 시퀀스의 각 요소의 개수를 셉니다.
이번엔 len을 사용해서 개수를 셀수도 있습니다.
def solution(array):
counter = Counter(array) # 각 요소의 빈도수를 세는 Counter 객체 생성
max_count = max(counter.values()) # 가장 많이 나온 빈도수
most_common = [key for key, value in counter.items() if value == max_count] # 가장 많이 나온 요소들의 리스트
if len(most_common) > 1: # 최빈값이 여러 개인 경우
return -1
else: # 최빈값이 하나인 경우
return most_common[0]