https://www.acmicpc.net/problem/2108
2108번: 통계학
첫째 줄에 수의 개수 N(1 ≤ N ≤ 500,000)이 주어진다. 단, N은 홀수이다. 그 다음 N개의 줄에는 정수들이 주어진다. 입력되는 정수의 절댓값은 4,000을 넘지 않는다.
www.acmicpc.net
https://github.com/stellaluminary/Baekjoon
GitHub - stellaluminary/Baekjoon
Contribute to stellaluminary/Baekjoon development by creating an account on GitHub.
github.com
문제에서 요구하는 산술평균, 중앙값, 최빈값, 범위를 출력한다.
첫째 줄에는 산술평균을 출력한다. 소수점 이하 첫째 자리에서 반올림한 값을 출력한다.
둘째 줄에는 중앙값을 출력한다.
셋째 줄에는 최빈값을 출력한다. 여러 개 있을 때에는 최빈값 중 두 번째로 작은 값을 출력한다.
넷째 줄에는 범위를 출력한다.
다만 최빈값에 대해서는 collections.Counter를 활용한 dict 형식의 값을 받는다.
첫 번째 예제에 대한 결과 : Counter({-2: 1, 1: 1, 2: 1, 3: 1, 8: 1})
이를 기반으로 최빈값을 구하는데 이때 여러 개가 존재할 가능성을 염두하여 구현을 진행한다.
from collections import Counter
import sys
input = sys.stdin.readline
n = int(input())
l = []
for i in range(n):
l.append(int(input()))
l.sort()
print(round(sum(l)/n))
print(l[n//2])
cnt = Counter(l)
t = []
res = 0
for i in cnt:
if res < cnt[i]:
res = cnt[i]
t = [i]
elif res == cnt[i]:
t.append(i)
if len(t) == 1:
print(t[0])
else:
print(t[1])
print(l[-1]-l[0])
collections.Counter.most_common을 활용한 최빈값의 다른 표현 방법을 적용하였다.
만약 most_common을 적용하면 다음과 같이 표현된다.
1 번째 예제
[(-2, 1), (1, 1), (2, 1), (3, 1), (8, 1)]
3 번째 예제
[(-2, 2), (-1, 2), (-3, 1)]
4 번째 예제
[(0, 2), (-1, 1)]
from collections import Counter
import sys
input = sys.stdin.readline
n = int(input())
l = []
for i in range(n):
l.append(int(input()))
l.sort()
print(round(sum(l)/n))
print(l[n//2])
cnt = Counter(l).most_common(2)
if len(cnt) > 1:
if cnt[0][1] == cnt[1][1]:
print(cnt[1][0])
else:
print(cnt[0][0])
else:
print(cnt[0][0])
print(l[-1]-l[0])