15. Median


#1

this is the code that I could come up with and I don't see what the problem is...

here is the error code I got:

ANY HELP IS APPRECIATED! Thanks!


#2

Your else statement is incorrect, because you are calling a function result with a list divided by a float. You need to get a number for s if you want to divide it, so maybe len(s)? Also, you don't have to assign it to result each time. You can just have, for the if statement,

return (n1+n2)/2

and for the else,

return (len(s)/2)

if that is what you are trying to do.


#4

This was my result

And the error


#5

There are two special cases not tested in the above:
1. The empty list []
2. Single element list [1]

Test the inputs for these and discard, else proceed.


#7

I'm sorry but I'm not following what you're saying.


#8

5 posts were split to a new topic: Look at my code and understand what you mistake


#9

def median(sample):
    n = len(sample)
    if n > 0:
        sample.sort()
        n /= 2
        if n % 2 !=0:
            return sample[n]
        else:
            return (sample[n] + sample[n-1]) / 2.0
    else:
        return "Input Error!"

The above rejects an empty list. The single element is worked out in the normal flow for odd number of samples. 1/2 is 0, the index of the single element.