미소를뿌리는감자의 코딩
[백준 2024/02/22] 2108번 통계학 본문
728x90
https://www.acmicpc.net/problem/2108
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
'코딩 테스트 > 백준' 카테고리의 다른 글
[백준 2024/02/22] 1002번 터렛 - python ver. (0) | 2024.02.22 |
---|---|
[백준 2024/02/22] 5052번 전화번호 목록 (1) | 2024.02.22 |
[백준 2024/02/22] 10814번 나이순 정렬 (0) | 2024.02.22 |
[백준 2024/02/22] 2751번 수 정렬하기 2 (0) | 2024.02.22 |
[백준 2024/02/21] 1011번 Fly me to the Alpha Centauri - python ver. (1) | 2024.02.21 |