Median - What's wrong here?


#1

What's wrong with my median code?

I receive:

Oops, try again. median([1]) resulted in an error: list index out of range

def median (nums):
    s = sorted(nums)
    halflen= len(nums)/2.0
    if len(s) % 2 == 0 :
        median = (s[int(halflen)] + s[int(halflen + 1)]) / 2.0
    else:
        median = s[int(halflen + 0.5)]
    return median

#2

You have an error message saying that you used an index that's too large or too small, I suggest using prints to find out what indexes you were using and then reconsider how you got a value that isn't a valid index.

You should also stick to integer operations when computing indexes. You should generally avoid floats if you don't specifically need to approximate numbers.


#3

I don't understand the comment about integers, could you elaborate a bit?

Also, I took another stab at it, but I'm not quite there.

Oops, try again. median([4, 5, 5, 4]) returned 5.0 instead of 4.5

'''
def median (nums):
s = sorted(nums)
halflen= len(nums)/2.0
if len(s) ==1:
median = s[0]
elif len(s) % 2 == 0 :
median = (s[int(halflen)] + s[int(halflen + 1)]) / 2.0
else:
median = s[int(halflen + 0.5)]
return median
'''


#4

Floats are approximations, so you if you for example have approximately 2, then that might be 1.999999 or 2.000001, converting those to int will have very differenty results, one of them becomes a much smaller number

This is unlikely to be what causes your incorrect result, it's a secondary problem. Computing which index to use is something exact, so there shouldn't be any approximating involved, and there should especially not be large differences in outcome based on which way the approximations are off. simple as that

Add prints to your code to print out what it's doing. Like looking over the shoulder of someone solving a math problem, checking that they're doing it right.


#5

Did you sort it sucessfully?
Identify whether odd/even length?
Get the right index(es)?
Obtain the values at those indexes?
add them together correctly?
divide them by the right amount?
return the right result?

Those are all things you already know that they need to be done in your function, and they're all things you can check if you got them right and by so doing you find out what's wrong


#6

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