백준 통계학 문제에서 최빈값을 구할 때 반복문과 count() 내장 함수를 사용하면 시간초과가 발생한다. 이를 해결하기 위해서 collections 라이브러리의 Counter에 포함된 Counter(arr).most_common()를 사용한다. 이는 괄호 안의 리스트의 원소와 빈도를 묶은 튜플을 리스트로 반환해준다.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import sys | |
from collections import Counter | |
n = int(sys.stdin.readline()) | |
arr = [] | |
for i in range(n): | |
arr.append(int(sys.stdin.readline())) | |
arr.sort() | |
print(round(sum(arr)/n)) | |
print(arr[n//2]) | |
k = Counter(arr).most_common() | |
if len(k) > 1 and k[0][1] == k[1][1]: | |
print(k[1][0]) | |
else: | |
print(k[0][0]) | |
print(max(arr)-min(arr)) |
python.flowdas.com/library/collections.html
collections --- 컨테이너 데이터형 — 파이썬 설명서 주석판
collections --- 컨테이너 데이터형 소스 코드: Lib/collections/__init__.py 이 모듈은 파이썬의 범용 내장 컨테이너 dict, list, set 및 tuple에 대한 대안을 제공하는 특수 컨테이너 데이터형을 구현합니다. named
python.flowdas.com
정말정말 중요한 컬렉션 라이브러리
1. deque
2. Counter



'코딩테스트 준비' 카테고리의 다른 글
DP (0) | 2021.02.19 |
---|---|
백준 9184 재귀함수 + 다이나믹 프로그래밍 + 딕셔너리 - 튜플 키 (0) | 2021.02.18 |
람다를 통한 다중 튜플 정렬 (0) | 2021.02.18 |
계수정렬 (0) | 2021.02.17 |
리스트 입력받기 꿀팁 (0) | 2021.02.17 |