[백준 #2108] 통계학(Python)

Updated:

문제 설명

예제 입출력

산술평균과 중앙값, 범위는 쉽게 구할 수 있었는데, 최빈값에서 막혀있었다. Counter 모듈은 알았지만 그 뒤로 해결이 안되어 Counter에 대해 검색을 해봤더니 most_common이라는 아주 좋은 녀석이 있었다. most_common(n)을 사용하면 가장 빈도가 높은 녀석을 n개까지 찾아준다. 이 때 반환되는 값은 tuple의 list로 반환된다. 예시를 통해 자세히 살펴보자.

N=[1,2,2,3,4]
cnt=Counter(N)
print(cnt)
most_cnt=cnt.most_common(2)
print(most_cnt)

결과 화면

Counter({2: 2, 1: 1, 3: 1, 4: 1})
[(2, 2), (1, 1)]

이제 위의 개념을 활용하여 최빈값도 구할 수 있다.

Code


import sys
from collections import Counter
N=int(sys.stdin.readline()) #테스트 케이스 입력
li=[int(sys.stdin.readline()) for i in range(N)] #숫자들 입력

if N==1:  #N이 1이라면 연산이 필요하지 않음
    print(li[0])
    print(li[0])
    print(li[0])
    print(0)
    sys.exit()

li.sort()
print(int(round(sum(li)/N, 0))) #첫번째 출력(산술평균)
print(li[N//2]) #두번째 출력(중앙값)
cnt=Counter(li)
most_cnt=cnt.most_common(2)
if most_cnt[0][1]==most_cnt[1][1]:
    print(most_cnt[1][0])
else:
    print(most_cnt[0][0]) #세번째 출력(최빈값)
print(li[-1]-li[0]) #네번째 출력(범위)

Leave a comment