Median Help Needed


#1

When I run this code with the sequence (1, 34, 1, 6, 8, 0) it returns 4.5 instead of 3.5.
Anyone know what I'm doing wrong?

Thanks

def median(num):
    med0 = 0
    med1 = 0
    med2 = 0
    num.sort()
    #find mid point of sequence
    mid = len(num) / 2
    #finding out if list is even
    if len(num) % 2 == 0:
        #getting midpoint - 1
        med1 += num[mid-1]
        #getting midpoint - 2
        med2 += num[mid+1]
        print med2
        print med1
        #averaging midpoints
        med0 = (med1 + med2) / 2.0
    else:
        #if sequence length is odd
        med0 += num[mid]
    #returning the median
    return med0

#2

med2 is wrong. The middle two indexes are length/2 (mid, not mid + 1) and mid - 1.


#3

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.