Median - something wrong in logic


#1



I tired multiple variations of how to get the right answer but there is something wrong with my logic that I can't figure out.


mid = ( (num[numL / 2]), (num[(numL / 2) -1 ] ) )
Oops, try again. median([4, 5, 5, 4]) returned 5.0 instead of 4.5

mid = ( (num[numL / 2]), (num[(numL / 2) ] - 1 ) )
Oops, try again. median([1, 34, 1, 6, 8, 0]) returned 5.5 instead of 3.5


If I change the numbers given, it changes between working and not working depending on how my 'mid' variable is setup.
mid = [ (num[ (numL / 2) - 1 ] ), (num[numL / 2]) ]
vs
mid = [ (num[ (numL / 2) ] -1 ), (num[numL / 2]) ]

please explain how to go about solving it, don't solve.


def median(num):
    numS = sorted(num)
    print "num sort", numS
    numL = len(numS)
    print "num length", numL
    numR = range(0, len(numS))
    print "num range", numR
    
    mid = [ (num[ (numL / 2) - 1 ] ), (num[numL / 2]) ]
    print "mid ", mid
    
    if numL % 2 == 0:
        mean = (mid[0] + mid[1]) / 2.0
        return mean
        print 
    elif numL % 2 != 0:
        mean = numL / 2
        return numS[mean]
    print "mean ", mean

print median([4, 5, 5, 4])
print median([1, 34, 1, 6, 8, 0])


#2

NVM!!

I realized my mistake. which was I kept calling num instead of numS (sorted)

mid = [ (numS[ (numL / 2) - 1 ] ), (numS[numL / 2]) ]


#3

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