[프로그래머스] 최빈값구하기

이름이름·2023년 3월 26일
0

프로그래머스

목록 보기
2/2

Counter (사용한 라이브러리)

Counter() : 문자열이나, list 의 요소를 카운팅하여 많은 순으로 딕셔너리형태로 리턴한다

array = [1,2,2,2,3,3,3,4]
count = Counter(array)
-> {3: 3, 1: 1, 2: 1, 4: 1})

most_common() : 개수가 많은 순으로 정렬된 튜플 배열 리스트를 리턴한다

array = [1,2,2,2,3,3,3,4]
count = Counter(array).most_common()
->[(2, 3), (3, 3), (1, 1), (4, 1)]
  # 보면 (숫자,갯수)로 나타내주고 갯수가 같으면 숫자도 오름차순으로 정렬해줌 

원래 코드 (에러)

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

컴파일 에러가 난 코드다
array가 [1,1]일 경우 most배열은 1개 밖에 없기때문에 most[1][1]부분에서 에러가 난다

수정 코드 (정답)

from collections import Counter
def solution(array):
    counter = Counter(array)
    most = counter.most_common()
    
    if(len(most)==1):  //수정한 부분
        return array[0]
    else:
        if(most[0][1]==most[1][1]):
            return -1
        else:
            return most[0][0]

most배열 크기가 1일 경우를 따로 처리해 주었다

profile
공부 정리

0개의 댓글