본문 바로가기

코테 공부/python

Python 최빈값 collections 모듈의 Counter 클래스, 안풀린 로직

collections 모듈의 Counter 클래스

Counter는 사전(dict) 클래스의 하위 클래스로 리스트나 튜플에서 각 데이터가 등장한 횟수를 사전 형식으로 돌려준다.

Counter 클래스의 most_common() 메쏘드는 등장한 횟수를 내림차순으로 정리

내부 값도 배열처럼 접근 가능

numbers = [1, 2, 3, 3, 4, 4, 4, 5, 5]
from collections import Counter
cnt = Counter(numbers)
cnt.most_common() #등장 회수 내림차순으로
print(cnt)  #[(4, 3), (3, 2), (5, 2), (1, 1), (2, 1)]
print(mode[0][0])  #4

그래서 이건 되었는데

from collections import Counter
def solution(array):
    cnt = Counter(array).most_common()
    print(cnt)
    if len(cnt) == 1:
        return cnt[0][0]
    if cnt[0][1] == cnt[1][1]:
        return -1
    return cnt[0][0]

이건 왜 안될까...

    array.sort()
    count_arr = {}
    count = 0
    
    if len(array) == 1:
        return array[0]
    
    for i in range(0, len(array)):
        if i >= 1:
            if array[i] == array[i-1]:
                continue
        count_arr[array[i]] = array.count(array[i])

    print(count_arr)

    max_value = max(count_arr.values())
    print(max_value)
    
    for j in count_arr:
        if count_arr[j] == max_value:
            count += 1
            
    if count >= 2:
        return -1
    else:
        for n in count_arr:
            if count_arr[n] == max_value:
                return count_arr[n]