본문 바로가기

Data-science/statistics

[basic-statitics] hackkerank 10일 기초 통계 code study 1일차

728x90

www.hackerrank.com/challenges/s10-basic-statistics/problem

 

Day 0: Mean, Median, and Mode | HackerRank

Compute the mean, median, mode, and standard deviation.

www.hackerrank.com

평균, 중앙값, 모드를 구하는 건데 엄청 복잡하게 구현한 것 같다.

# Enter your code here. Read input from STDIN. Print output to STDOUT

import sys 

numbers = []
mean = 0
median = 0 
mode_dict = {}
for i, line in enumerate(sys.stdin):
    if i == 0:
        length = int(line)
        continue
    else:
        nums = list(map(lambda x:float(x), line.split(' ')))
        for num in nums:
            small_k = num
            mode_dict[num] = mode_dict.get(num, 0) + 1


nums = sorted(nums)

mean = sum(nums)/length
if length % 2==0:
    median = (nums[length//2-1] + nums[length//2])/2.0
else:
    median = nums[length//2]

max_value = 0

for k,v in mode_dict.items():
    if v > max_value:
        max_value = v
        small_k = k
    elif v == max_value:
        if k < small_k:
            max_value = v
            small_k = k
    
mode = small_k


sys.stdout.write(f'{mean}\n{median}\n{mode:.0f}')

어쨌든 맞았다.