티스토리 뷰

반응형

 

 

 문제

 

www.acmicpc.net/problem/2108

 

2108번: 통계학

첫째 줄에 수의 개수 N(1 ≤ N ≤ 500,000)이 주어진다. 그 다음 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
from collections import Counter
from sys import stdin
 
input = stdin.readline
= int(input())
n_list = [0 for _ in range(n)]
for i in range(n):
    n_list[i] = int(input())
n_list.sort()
# 산술평균
print(round(sum(n_list) / n))
# 중앙값
print(n_list[n // 2])
# 최빈값
n_counter = Counter(n_list)
sorted_list = sorted(n_counter.most_common(), key=lambda x: (-x[1], x[0]))
if len(sorted_list) == 1:
    print(sorted_list[0][0])
else:
    if sorted_list[0][1== sorted_list[1][1]:
        print(sorted_list[1][0])
    else:
        print(sorted_list[0][0])
# 범위
print(n_list[-1- n_list[0])
 
cs

 

 

 

 

 

 

 

 

 해설

 

- Counter의 most_common을 활용하여 발생 횟수가 많은 순으로 정렬하여 (element, 발생 횟수)를 요소로 갖는 리스트를 반환한다.

 

 

 

 

 

 

 

 새로 학습한 것 & 실수 

 

- Counter를 활용하여 반복 횟수를 출력한다.

 

 

 

 

 

 

 

 

반응형
댓글