python 최빈값 구하기

도리·2025년 1월 10일
  1. array값을 index로
def solution(array):
    # array 수를 인덱스로 사용해서 숫자 개수 구하자
    # array = [1,2,2,3,4]
    count = [0]*(max(array)+1)
    # [0,0,0,0,0]
    
    for i in array:
        count[i] += 1
     #[0,1,2,1,1]
    
    c = 0 # 최빈값 개수 구하기 
    # 내가 궁금한건 하나, max(count)와 같은 값이 있나?
    
    for i in count:
        if i == max(count):
            c += 1
    
    if c>1 :
        answer= -1
    else : # max(count)가 value인 index 추출
        answer = count.index(max(count))
    
    ## dictionary 이용할 수도 있다...
    return answer

2.dictionary를 이용해서

def solution(array):
    # 1. 각 원소의 빈도수를 계산
    frequency = {}
    for num in array:
        if num in frequency:
            frequency[num] += 1
        else:
            frequency[num] = 1
    
    # 2. 가장 빈번하게 나오는 원소의 빈도수를 찾는다
    max_frequency = max(frequency.values())

    # 3. 최빈값이 하나인지, 여러 개인지 판별
    mode_values = [key for key, value in frequency.items() if value == max_frequency]

    if len(mode_values) > 1:
        return -1
    else:
        return mode_values[0]

생각보다 어렵네ㅎㅎ;;

profile
인공지능응용학과 졸업예정..

0개의 댓글