코테
[백준 / Python] 2108번 : 통계학
개발자가 되고 싶어요
2023. 2. 3. 04:30
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
input = sys.stdin.readline
n = int(input())
numList = [0] * n
for i in range(n):
numList[i] = int(input())
numList.sort()
numDict = {}
for k in numList:
numDict[k] = numList.count(k)
maxIndex = [k for k,v in numDict.items() if max(numDict.values()) == v]
print(round(sum(numList)/n))
print(numList[(n//2)])
if len(maxIndex) >= 2:
print(maxIndex[1])
else:
print(maxIndex[-1])
print(max(numList)-min(numList))
|
cs |
시간초과....
최빈값을 찾기 위해 사용한 count 함수가 원인인 것 같다.
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
|
from collections import Counter
import sys
input = sys.stdin.readline
n = int(input())
numList = [0] * n
for i in range(n):
numList[i] = int(input())
numList.sort()
counterList = Counter(numList).most_common(2)
print(round(sum(numList)/n))
print(numList[(n//2)])
try:
if counterList[0][1] == counterList[1][1]:
print(counterList[1][0])
else:
print(counterList[0][0])
except:
print(counterList[0][0])
print(max(numList)-min(numList))
|
cs |
count를 사용하지 않고 최빈값을 찾기 위해 collections 모듈의 Counter 클래스를 사용했다. 그 중 내부 메소드인 most_common 함수를 사용하여 두 개의 최빈값과 빈도수를 새로 만든 변수에 저장하고 조건에 따라 출력을 다르게 해서 모든 조건에서 정답을 만족시키게끔 만들었다.
이번 문제에서 count를 사용하지 않아도 리스트의 각 요소 빈도를 계산할 수 있는 Counter 클래스에 대해 알게 되었다.