프로그래밍/Python

백준_python 2108번 통계학(시간초과, collections.Counter 모듈)

O'bin 2024. 4. 8. 23:48

<문제 링크>

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

 

2108번: 통계학

첫째 줄에 수의 개수 N(1 ≤ N ≤ 500,000)이 주어진다. 단, N은 홀수이다. 그 다음 N개의 줄에는 정수들이 주어진다. 입력되는 정수의 절댓값은 4,000을 넘지 않는다.

www.acmicpc.net

 

<정답 코드>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
import sys
from collections import Counter
 
# input()으로 입력 받으면 시간초과 발생
input = sys.stdin.readline  
= int(input())
nums = [int(input()) for _ in range(n)]
 
nums.sort()
 
mean = round(sum(nums) / n) # 1. 산술평균(소수점 이하 첫째 자리에서 반올림한 값 출력)
 
median = nums[n // 2]       # 2. 중앙값
 
# 3.최빈값
freq = Counter(nums)
most_com = freq.most_common()
max_freq = most_com[0][1]
 
modes = [val for val, freq in most_com if freq == max_freq]
 
mode = modes[0if len(modes) == 1 else modes[1]
 
range_val = nums[-1- nums[0]  # 4. 범위
 
print(mean)
print(median)
print(mode)
print(range_val)
cs