문제
# 첫째 줄에는 산술평균을 출력한다. 소수점 이하 첫째 자리에서 반올림한 값을 출력한다.
# 둘째 줄에는 중앙값을 출력한다.
# 셋째 줄에는 최빈값을 출력한다. 여러 개 있을 때에는 최빈값 중 두 번째로 작은 값을 출력한다.
# 넷째 줄에는 범위를 출력한다.
나의 풀이
1. 산술평균, 중앙값, 최빈값, 범위를 출력한다.
2. 산술평균은 반올림 처리
3. 최빈값을 구하고 key들만 모은 리스트 생성 (collections.Counter(), most_common() 사용)
최빈값이 여러개일 경우 최빈값 중 두 번째로 작은 값을 출력
import collections
import sys
N = int(sys.stdin.readline())
arr = []
if N % 2 == 1:
for i in range(N):
M = int(sys.stdin.readline())
arr.append(M)
arr.sort()
count_list = collections.Counter(arr).most_common()
max = count_list[0][1]
count_list_1 = []
for i in range(len(count_list)):
value = count_list[i][1]
count_list_1.append(value)
if count_list_1.count(max) != 1:
count_max = count_list[1][0]
else:
count_max = count_list[0][0]
ss = round(sum(arr) / N)
center = arr[N // 2]
range = arr[-1] - arr[0]
print(ss)
print(center)
print(count_max)
print(range)
- 초반에는 최빈값을 구하기 위해
collections.Counter(list)
를 쓴 뒤,
value로 key값을 반환하기 위해
reverse_dict= dict(map(reversed, count_dict.items()))
를 사용하여 구하려 했으나 최빈값 중 두번쨰로 작은 값을 반환하기에 어려워 다시 검색하여 most.common()
활용
collenctions.Counter()
- collections.Counter(a) : a에서 요소들의 개수를 세어, 딕셔너리 형태로 반환합니다. {문자 : 개수} 형태
most_common()
- 최빈값 구하기
- collections.Counter(a).most_common(n) : a의 요소를 세어, 최빈값 n개를 반환합니다. (리스트에 담긴 튜플형태로)
import collections
arr = [1, 2, 3, 4, 4, 4, 4, 5, 6]
count_dict = collections.Counter(arr)
print(count_dict)
count_list = collections.Counter(arr).most_common()
print(count_list)
count_list_1 = collections.Counter(arr).most_common(3)
print(count_list_1)
counter, most_common