#2108 통계학
1. from collections import Counter 모듈 사용
- Counter()를 사용하면 다음과 같이 빈도수와 리스트를 dictionary 형태로 저장해준다.
- most_common()을 사용하면 빈도수로 정렬하고 dictionary를 list[tuple()] 형태로 저장해준다.
from collections import Counter
colors = Counter(['blue', 'green', 'red', 'blue','red','blue'])
print(colors)
# Counter({'blue': 3, 'red': 2, 'green': 1})
print(colors.most_common())
# [('red', 3), ('blue', 2), ('green', 1)]
print(colors.most_common(2))
# 가장 많은 것 부터 2개 출력
# [('red', 3), ('blue', 2)]
2. Python 내장 round 함수 사용
- round()를 사용하면 반올림을 해준다.
round(3.1415)
# 결과는 3
round(3.1415, 2)
# 결과는 3.14
round(3.1415, -1)
# 결과는 30.0
round(3.5)
round(4.5)
# 오사오입을 따르기에 결과는 둘 다 4
3. 빈도수를 측정하는 freq함수에 대해
- 빈도수가 같은 수가 있을 경우 두번째 숫자 출력
- most_common()의 결과가 유일할 경우 해당 숫자를 출력
4. 전체 코드
import sys
from collections import Counter
input = sys.stdin.readline
n = int(input())
num_list = []
for _ in range (n):
num_list.append(int(input()))
def mean(a):
return round(sum(a)/n)
def median(a):
a.sort()
return a[n//2]
def freq(a):
cnt = Counter(a).most_common()
if len(a)>1:
if cnt[0][1]==cnt[1][1]:
fre = cnt[1][0]
else:
fre = cnt[0][0]
else:
fre = cnt[0][0]
return fre
def scope(a):
return (a[-1] - a[0])
# a[-1] : 가장 마지막 요소
print(mean(num_list))
print(median(num_list))
print(freq(num_list))
print(scope(num_list))반응형