하루일문
[백준] 2108번 통계학(파이썬) 본문
풀이
import sys, math
n = int(sys.stdin.readline())
nums = []
for _ in range(n):
num = int(sys.stdin.readline())
nums.append(num)
# 오름차 정렬
s_n = sorted(nums)
#평균
#round = 반올림
avg = round(sum(nums)/n)
#중앙값
# math.ceil = 올림
mid = s_n[math.ceil(len(nums)//2)]
#최빈값
#딕셔너리 생성
cnt = {}
#딕셔너리에 넣고 있으면 카운트
for i in range(len(s_n)):
if s_n[i] not in cnt:
cnt[s_n[i]] = 1
else:
cnt[s_n[i]] += 1
# value값이 value에서 제일 큰값과 같다면 append
same = []
for key, value in cnt.items():
if value == max(cnt.values()):
same.append(key)
# 리스트에 길이로 최빈값의 중복을 확인
if len(same) == 1:
look = same[0]
else:
look = same[1]
#범위
side = s_n[len(nums)-1]- s_n[0]
# 프린트
print(avg, mid, look, side, sep = "\n")
함수를 사용하지 않고 풀이해보았다.
최빈값의 함수 풀이는 다음과 같다.
최빈값 함수풀이
T = int(input())
num = []
for t in range(T):
n = int(input())
num.append(n)
# collections의Counter를 부른다(개수를 세주는 함수)
from collections import Counter
# Counter 적용
cnt=Counter(num)
# most_common() = 가장 많이 카운트 된 순위
common=cnt.most_common(2)
# num 길이가 1보다 크면
if len(num)>1:
# 두 수의 카운트가 같다면
if common[0][1]==common[1][1]:
print(common[1][0])
# 다르다면
else:
print(common[0][0])
else:
print(common[0][0])
'algorithm > baekjoon' 카테고리의 다른 글
[백준] 4963 섬의 개수(파이썬) (0) | 2023.02.13 |
---|---|
[백준] 1260 DFS와 BFS(파이썬) (0) | 2023.02.13 |
[백준] 2751번 수 정렬하기 3 (파이썬) (0) | 2023.02.11 |
[백준] 2751번 수 정렬하기 2 (파이썬) (0) | 2023.02.10 |
[백준] 2563번 색종이 (파이썬) (0) | 2023.02.09 |