[백준] 2108번 통계학

오혜수·2022년 3월 23일
0

코딩 테스트

목록 보기
51/61

링크 : https://www.acmicpc.net/problem/2108

문제

풀이

최빈값에서 많이 애먹었다.. collections.Counter를 쓰지 않고 해결해보려고 했지만 실패!

collections.Counter(array).most_common()을 하면 튜플 형식으로 원소의 개수가 주어진다. 이걸 이용해서 두번째 최빈값을 구했다.

그런데, array에 하나의 값이 여러 번 들어갔을 때 Counter에서 오류가 났다. 이를 해결하기 위해 if문 안에 len(Counter(sorted(array)).most_common() == 1을 넣었다.

참고로, Counter(sorted(array)).most_common()을 하면 tuple[1], tuple[0] 순으로 sort된다.

import sys
from collections import Counter
input = sys.stdin.readline

n = int(input())
array = [int(input()) for _ in range(n)]

print(round(sum(array)/len(array)))

print(sorted(array)[len(array)//2])


if len(Counter(sorted(array)).most_common()) == 1:
    print(array[0])
elif Counter(sorted(array)).most_common()[0][1] ==  Counter(sorted(array)).most_common()[1][1]:
    print(Counter(sorted(array)).most_common()[1][0])
else:
    print(Counter(sorted(array)).most_common()[0][0])

print(max(array)-min(array))

0개의 댓글