본문 바로가기
백준알고리즘/정렬

(Python/🥈3)백준 알고리즘 2108번: 통계학

by windy7271 2022. 5. 24.
728x90
반응형

문제 출처:https://www.acmicpc.net/problem/2108

 

2108번: 통계학

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

www.acmicpc.net

풀이:

import sys
from collections import Counter # 최빈값 구하는 클래스


N = int(sys.stdin.readline())   		# input 보다 빠름
array = list()							# 숫자들 들어갈 리스트 하나 만들어줌
for _ in range(N):
    array.append(int(sys.stdin.readline()))	#포문 돌려서 리스트에 추가
sort = sorted(array)						# 리스트 정렬

print(round(sum(sort)/N))                      # 산술평균
print(sort[N//2])                         	   # 중앙값

count = Counter(sort).most_common(2)           # 빈도수가 높은 2개 함수 가져옴
if len(count) > 1 and count[0][1] == count[1][1]:   # 2개 이상일때 또 갯수도 같을때
    print(count[1][0])								# 두 번째꺼 출력
else:
    print(count[0][0])								# 첫 번째꺼 출력

print(max(array)-min(array))             	# 최대범위

 

쉬운 문제다 

최빈값 구하는거 빼고

최빈값 구하는 방법은 Counter 를 사용하여 딕셔너리 형태로 받아와서 비교 해줘야 한다.

most_common() 은 데이터의 개수가 많은 순으로 정렬된 배열을 리턴한다

() 에 2 를 넣었으니 2개를 리턴한다

 

 

https://www.daleseo.com/python-collections-counter/

 

[파이썬] collections 모듈의 Counter 클래스 사용법

Engineering Blog by Dale Seo

www.daleseo.com

 

반응형

댓글