[백준] 2108번(통계학)

·2023년 2월 7일

백준 문제풀이

목록 보기
40/159

백준 2108번


최종 제출 코드

import sys
from collections import Counter

input = sys.stdin.readline
num = int(input())
num_list = []
sum = 0
count = 0

for i in range(num):
  number = int(input())
  num_list.append(number)
  sum += number

num_list.sort()

nums = Counter(num_list).most_common()

xmean = round(sum/num)
xmedian = num_list[num//2]
xrange = num_list[num-1]-num_list[0]

# 입력값의 개수가 1개일수도 있음
if len(nums) > 1:
    if nums[0][1] == nums[1][1]:
        xmode=nums[1][0]
    else:
        xmode=nums[0][0]
else:
    xmode=nums[0][0]

print(xmean)
print(xmedian)
print(xmode)
print(xrange)
  • 최빈값 구하는 코드 참고(출처)

Counter

  • Counter(): 문자열이나, list의 요소를 카운팅하여 많은 순으로 딕셔너리형태로 리턴
  • most_common(): 개수가 많은 순으로 정렬된 튜플 배열 리스트를 리턴
from collections import Counter

my_list = [6,2,12,7,9,6]
my_list.sort()

print(Counter(my_list))

lists = Counter(my_list).most_common()
print(lists)
Counter({6: 2, 2: 1, 7: 1, 9: 1, 12: 1})    #Counter()
[(6, 2), (2, 1), (7, 1), (9, 1), (12, 1)]   #Counter().most_common()

출처

profile
백엔드 개발자가 되고 싶어요(22.8.15~)

0개의 댓글