[BOJ] 2108번 통계학(counter, most_common)

호호빵·2022년 8월 25일
0

Algorithm

목록 보기
16/46

문제

# 첫째 줄에는 산술평균을 출력한다. 소수점 이하 첫째 자리에서 반올림한 값을 출력한다.
# 둘째 줄에는 중앙값을 출력한다.
# 셋째 줄에는 최빈값을 출력한다. 여러 개 있을 때에는 최빈값 중 두 번째로 작은 값을 출력한다.
# 넷째 줄에는 범위를 출력한다.

나의 풀이

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()                              # 숫자들을 arr에 넣고 sort

count_list = collections.Counter(arr).most_common()  # Counter를 사용해 각각의 개수를 dict 형태로 받고
max = count_list[0][1]                               # most_common(n)을 사용해 최빈값 n개를 리스트에 담긴 튜플형태로 반환
                                                     # 가장 많이 나온 횟수를 max로 저장
count_list_1 = []                                    # 최빈값의 순서대로 나온 key들을 저장할 리스트

for i in range(len(count_list)):                     # key들만 저장
    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)
# Counter({4: 4, 1: 1, 2: 1, 3: 1, 5: 1, 6: 1})

count_list = collections.Counter(arr).most_common()
print(count_list)
# [(4, 4), (1, 1), (2, 1), (3, 1), (5, 1), (6, 1)]

count_list_1 = collections.Counter(arr).most_common(3)
print(count_list_1)
# [(4, 4), (1, 1), (2, 1)]  최빈값 3개만


counter, most_common

profile
하루에 한 개념씩

0개의 댓글