[BOJ] 7568번 통계학 (Python)

천호영·2022년 3월 17일
0

알고리즘

목록 보기
1/100
post-thumbnail

첫 시도

import collections
N = int(input())

arr = [int(input()) for _ in range(N)]

sorted_arr = sorted(arr)

print(round(sum(arr)/N))
print(sorted_arr[len(arr)//2])
print(collections.Counter(arr).most_common(1)[0][0])
print(sorted_arr[-1]-sorted_arr[0])

하지만 시간 초과 발생. 이번에도 문제는 input()이었다. 따라서 sys.stdin.readline()으로 변경해줬다.

import collections,sys
N = int(input())

arr = [int(sys.stdin.readline()) for _ in range(N)]

sorted_arr = sorted(arr)

print(round(sum(arr)/len(arr)))
print(sorted_arr[len(arr)//2])
print(collections.Counter(arr).most_common(1)[0][0])
print(sorted_arr[-1]-sorted_arr[0])

이번엔 틀렸습니다여서 원인을 분석해보니 문제를 제대로 읽지 않았다. 최빈값이 여러 개 있을 때 두 번째로 작은 값을 출력해주도록 변경했으나 또 다시 틀렸습니다.

collections.Counter에 정렬된 리스트를 전달하니 통과되었다,,!

import collections,sys
N = int(input())

arr = [int(sys.stdin.readline()) for _ in range(N)]

sorted_arr = sorted(arr)
print(round(sum(arr)/N))
print(sorted_arr[N//2])

most_common_items = collections.Counter(sorted_arr).most_common()
if len(most_common_items) >=2 and most_common_items[0][1] == most_common_items[1][1]:
  print(most_common_items[1][0])
else:
  print(most_common_items[0][0])
  
print(sorted_arr[-1]-sorted_arr[0])

그 이유는 최빈값이 있을때 그 안에서 수들이 정렬되어있어야 하기 때문이다.
코드로 설명해보면, 결과는 다음과 같이 나온다.

print(Counter(arr).most_common())
print(Counter(sorted_arr).most_common())

profile
성장!

0개의 댓글