미소를뿌리는감자의 코딩

[백준 2024/02/22] 2108번 통계학 본문

코딩 테스트/백준

[백준 2024/02/22] 2108번 통계학

미뿌감 2024. 2. 22. 15:17
728x90

https://www.acmicpc.net/problem/2108

 

2108번: 통계학

첫째 줄에 수의 개수 N(1 ≤ N ≤ 500,000)이 주어진다. 단, N은 홀수이다. 그 다음 N개의 줄에는 정수들이 주어진다. 입력되는 정수의 절댓값은 4,000을 넘지 않는다.

www.acmicpc.net

 

1. 접근 방법

조금 직관적인 문제였다. 약간 까다로운 부분이라 함은 최빈값을 구하는 부분인 것 같다.

최빈값을 구하는 곳은 Counter를 이용해서 풀어주었다.

counter = Counter(nums) # 아이템, 횟수 로 정리됨.
Counter({1: 1, 2: 2, 3: 3}) # 딕셔너리와 유사한 형태로 저장

Counter를 이용하게 되면 이런 식으로 정리되게 된다.

 

이제 .most_common()을 통해서 제일 많이 반복된 횟수에 대해서 알 수 있다. -> 빈번하게 등장하는 요소부터 순서대로 정렬되어 반환

common = counter.most_common() # 다 반환
counter.most_common(2) #가장 빈번하게 등장하는 상위 2개의 요소 반환

##
counter = Counter([1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4])
print(counter.most_common())
# 출력 : [(4, 5), (3, 4), (2, 2), (1, 1)]

이런식으로 (요소, 횟수) 가 나오게 된다. 

 

여기서 common[0][1] 을 하게 된다면, 제일 많이 반복된 최빈값의 횟수를 알 수 있다. 그리고 이를 most_common_elements로 저장해 두었다.

 

하지만, 최빈값이 여러개일 수 있기 때문에, count가 most_common_elements와 같은 것들은 list에 그 값을 저장해 두었다.

 

이후 list의 길이가 1 이라면 index 0 반환,  길이가 1이 아니라면 ( 1보다 크다면) index 1 을 반환해 주었다.

왜냐하면 조건으로, '최빈값이 여러 개 있을 때에는 최빈값 중 두 번째로 작은 값을 출력한다' 가 있기 때문이다.

 

2. 코드

from collections import Counter


def append_values(nums, n):
    for i in range(n):
        nums.append(int(input()))
    nums.sort()


def arithmetic_mean(nums, n):
    return round(sum(nums)/n)


def median(nums, n):
    return nums[len(nums)//2]


def mode(nums, n):
    counter = Counter(nums)
    common = counter.most_common()
    highest_count = common[0][1]
    most_common_elements = [item for item, count in common if count == highest_count]
    most_common_elements.sort()

    return most_common_elements[0] if len(most_common_elements) == 1 else most_common_elements[1]


def _range(nums, n):
    return max(nums) - min(nums)


def main():
    nums = []
    n = int(input())
    append_values(nums, n)
    print(arithmetic_mean(nums, n))
    print(median(nums, n))
    print(mode(nums, n))
    print(_range(nums, n))


if __name__ == '__main__':
    main()
728x90