본문 바로가기
Programming/Contest

[checkio] Median

by NAMP 2016. 4. 6.

[checkio] Median

def checkio(data):

    #replace this for solution
    #return data[0]


    data = sorted(data)
    m = len(data)
    mh = int(m/2)

    if m % 2 == 1:
        return data[mh]
    else:
        return (data[mh - 1] + data[mh])/2



#These "asserts" using only for self-checking and not necessary for auto-testing
if __name__ == '__main__':
    assert checkio([1, 2, 3, 4, 5]) == 3, "Sorted list"
    assert checkio([3, 1, 2, 5, 3]) == 3, "Not sorted list"
    assert checkio([1, 300, 2, 200, 1]) == 2, "It's not an average"
    assert checkio([3, 6, 20, 99, 10, 15]) == 12.5, "Even length"
    print("Start the long test")
    assert checkio(list(range(1000000))) == 499999.5, "Long."
    print("The local tests are done.")

입력 배열을 정렬합니다.

입력 배열의 길이가 홀수인 경우와 짝수인 경우를 구별합니다.

홀수인 경우, 길이의 절반 인덱스를 반환하고,
짝수인 경우, 가운데 2개의 평균을 반환합니다.

출력
Start the long test
The local tests are done.

solutions

def checkio(data):
    off = len(data) // 2
    data.sort()
    med = data[off] + data[-(off + 1)]
    return med / 2

배열의 길이를 구한다.
배열을 정렬한다.

// double slash 를 사용한다.

>>> 10/3
3.3333333333333335
>>> 10//3
3

data[off] 의 값과 data[-(off+1)] 의 값을 더하고 나눈다.
배열의 길이가 홀수인 경우 data[off]의 값과 data[-(off+1)]의 값이 동일하다

[1,2,3,4,5] 인 경우, off 는 2 이다. 
data[2] = 2
data[-3] = 2 

배열의 길이가 짝수인 경우 가운데 2개의 값을 나타낸다.

[1,2,3,4] 인 경우, off 는 1 이다. 
data[1] = 2
data[-2] = 3

참고


'Programming > Contest' 카테고리의 다른 글

[coderbyte] First Reverse  (0) 2016.04.08
[checkio] House password  (0) 2016.04.07
[checkio] Non-unique Elements  (0) 2016.04.05
[codingame] The Descent  (0) 2014.12.13
[codingame] Power of Thor  (0) 2014.12.13

댓글