[백준/Python] 2108: 통계학

농담곰·2023년 7월 24일

백준

목록 보기
15/33

[백준/Python] 2108: 통계학

산술평균, 중앙값, 최빈값, 범위(최댓값과 최솟값의 차이)를 출력해야 한다.
크게 어려운 문제는 아니라고 생각했는데 제출해 보니 시간 초과가 났다.

문제는 입력을 input()으로 받은 점이었다. 파이썬의 입력에서 input()과 sys.stdin.readline()은 상당히 큰 시간 차이가 나기 때문이다.

최빈값을 구하는 부분은 collections 모듈의 Counter를 사용하였다. 유의할 점은 최빈값이 여러개 있을 때는 최빈값 중 두 번째로 작은 값을 출력해야 한다는 것이다.

소스코드


import sys
n = int(sys.stdin.readline())
arr = []

for i in range(n):
    arr.append(int(sys.stdin.readline()))

arr.sort()

# 최빈값
from collections import Counter
cnt = Counter(arr)
most = cnt.most_common()

print(round(sum(arr)/n))
print(arr[int(n/2)])
if n >= 2:
    if most[0][1] == most[1][1]:
        print(most[1][0])
    else:
        print(most[0][0])
else:
    print(most[0][0])
print(max(arr)-min(arr))

2개의 댓글

comment-user-thumbnail
2023년 7월 24일

정리가 잘 된 글이네요. 도움이 됐습니다.

1개의 답글