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

find the median

def median(x):
    a = sorted(x)
    if len(a) % 2 == 0:
        v = len(a) / 2
        n = v - 1
        end = (x[v] + x[n]) / 2.0
        return end
        m = len(a)/2
        return a[m]


so, you sort your list really nice:

a = sorted(x)

then you calculate the indexes very good, but then you want to get the numbers from the sorted lists (a[v] and a[n]) not the unsorted list (x[v] and x[n])

Hope this helps


def median(lisst):
    s = sorted(lisst)
    if (len(s) % 2) == 0:
        ni = (len(s) % 2.0)
        nl = ni + 1
        return (ni + nl) / 2
        return (len(s)/2.0)

This is my code it's a little different syntax than his, but its the same idea. I keep getting the error code:
Oops, try again. median([1]) returned 0.5 instead of 1


if the contains a odd number of items, why not simple return the items in the middle?


That's what I thought I was doing with my else statement.

returning the middle of my sorted list (len(s)/2.0)


No, the moment you want to access a indexed item at an array, you need to use square brackets:


this can only handle integers. So you better divide by 2 rather then 2.0


how would I call an index number when I don't know the full number of the inputted index?


You don't have to know?

if your list is 1 item long, 1 /2 = 0, which is where your median is indexed
if your list is 3 items long, 3 /2 = 1, which is where your median is indexed
if your list is 5 items long, 5 /2 = 2, which is where your median is indexed
if your list is 7 items long, 7/2 = 3, which is where your median is indexed

And so on


but you don't know how many items long your list is so how would you know what to return?


i just showed you, it doesn't matter. I could go on until infinity (i am not, for obvious reasons), but length of the list (for example 51) divided by two is 25, which is the middle item of the list, which is the median. Same for 9999, and so on


Okay but someone could input a 500 item list or a 5 item list, and you wouldn't know what they put in. I'm asking if there is some kind of universal way to divide the list by 2 and get the middle term without knowing how many items in the list.


If said list is n units long, the middle term when n is odd, is n / 2. So the median would be the middle term of a sorted sample space, s, as in s[n / 2].

When we seek the median of a list with a length that is even, then we need the middle two terms of the sorted list, which we then average (take their mean).

m = n / 2

(s[m] + s[m -1]) / 2.0

will give us the median of s.


I did not produce variables. The sorted list is checked on odd or even. And then calculates (agree is a bit confusing), but we do not create unnecessary variables

 if len( sp ) % 2 != 0:
        return sp[ ( len ( sp ) - 1 ) /2 ]
        return (sp [ len ( sp ) / 2 ] + sp [ ( len ( sp ) - 1 ) / 2 ] ) / 2.0