Skip to content

Instantly share code, notes, and snippets.

@riceluxs1t
Created November 11, 2015 05:44
Show Gist options
  • Save riceluxs1t/c492e23c71f7ca44792b to your computer and use it in GitHub Desktop.
Save riceluxs1t/c492e23c71f7ca44792b to your computer and use it in GitHub Desktop.
# -*- coding: utf-8 -*-
def compute_mean(alist):
sum_ = 0
for idx in range(len(alist)):
sum_ = sum_ + alist[idx]
return sum_/float(len(alist))
def compute_median(alist):
#alist = [3,2,1,5,7].sort()
#alist = [1,2,3,5,7]
#len(alist) = 6. len(alist)/2 , len(alist)/2 - 1
alist.sort()
if len(alist)%2 == 0: #even
median_ = (alist[len(alist)/2] + alist[len(alist)/2 - 1])/2.0
return median_
else: # odd
return alist[len(alist)/2]
def compute_mode(alist):
alist.sort()
# alist = [1,1,1,1,1,3,3,3,7,7, 9,9,9,9,9,9,9]
mode_ = -1 # 5
#모드숫자.
mode_value = -1 # 3
#모드 candidate 숫자.
mode_candidate_count = 0 # 6
#모드 candidate.
for idx in range(len(alist)):
#initialization.
if idx == 0:
mode_candidate_count += 1
# 이전 원소와 같다면 증가.
elif alist[idx] == alist[idx-1]:
mode_candidate_count += 1
if idx == len(alist)-1 and mode_candidate_count > mode_:
mode_value = alist[idx-1]
mode_ = mode_candidate_count
#이전 원소와 다르다면. 모드인지 판정.
else:
#판정.
if mode_candidate_count > mode_:
#모드로 셋팅.
mode_value = alist[idx-1]
mode_ = mode_candidate_count
#다시 초기화.
mode_candidate_count = 1
print 'index = {0}\n'.format(idx)
print alist[idx], mode_, mode_value, mode_candidate_count
#return mode of this @alist
return mode_value, mode_
def compute_mode_dictionary(alist):
alist.sort()
mode_dictionary = {}
for idx in range(len(alist)):
if alist[idx] not in mode_dictionary:
mode_dictionary[alist[idx]] = 1
else:
mode_dictionary[alist[idx]] += 1
max_ = -1
mode_ = -1
for key in mode_dictionary.keys():
print key, mode_dictionary[key]
if mode_dictionary[key] > max_:
max_ = mode_dictionary[key]
mode_ = key
return mode_, max_
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment