최빈값은 주어진 값 중에서 가장 자주 나오는 값을 의미합니다. 정수 배열 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]
'개발일기 [Python 파이썬]' 카테고리의 다른 글
장고 에러 발생시 해결 방안 (0) | 2024.04.12 |
---|---|
[Python Algorithm] Installation of Base Station (0) | 2024.04.09 |
[파이썬 정리] 조건문 & 반복문 (1) | 2024.03.28 |
[파이썬 정리] 리스트와 딕셔너리 (0) | 2024.03.26 |
[파이썬 정리] 변수 선언과 문자열 다루기 (0) | 2024.03.25 |