Median - so close but so far


#1




The code returns 4.0 instead of 4.5


def median(x):
    sorted(x)
    l = len(x)
    new = float(0.0)
    a = 0
    b = 0
    c = float(0.0)
    if l%2==0:
        a = int(l/2)
        b = a + 1
        a = x[a]
        b = x[b]
        c = float((a+b)/2)
        new = c
        
    else:
        l = l/2
        new = x[l]
        
    return new


#2

nvm, got it

 if l%2==0:
        a = int(l/2)
        b = a + 1
        a = float(x[a])
        b = float(x[b])
        c = float((a+b)/2)
        new = c

But, now I've got another error: median([6, 8, 12, 2, 23]) returned 12 instead of 8


#3

I suggest having an empty list for example new_list = [] that contains no reference to your parameter x,

then you can store your sorted method in that empty list like this,

new_list = sorted(x)

also do not refer to the len of your parameter x but now to your empty list that stores your sorted() list parameter,

l = len(new_list)

You can make your code cleaner and more elegant by discarding these three variables because your code can work without them and I will explain how,

Your if statementis ok as is,

now using only one return statement that takes your empty list and filters out the median by calculating the mean of two numbers,

return (new_list[a/2-1]+new_list[a/2-1+1])*0.5

this is similar to what you had on these three lines but only much shorter,

Finally your else statement,

You were on the right track but again no return statement and you do not calculate the mean of two numbers but this condition is when you have an odd number of results and want to find the median,

return sequence[a/2-1+1]


#4

Why does this part

Wouldn't ith code without it? -1 and +1 is 0, so I don't know what is it for. Can you explain?
And writing

Is for me actually unreadable, so I prefer my code :stuck_out_tongue:


#5

You have to read it as a whole,

2-1+1 = 2

and your code will not work until you calculate the mean of the two central numbers correctly. :slight_smile:


#6

DAAAAAAAAAMN,why my new list isn't sorted? It's pissing me off...

def median(x):
    x.sort()
    new = x
    l = len(x)
    
    a = 0
    b = 0
    if l == 1:
        for i in new:
            i = int(i)
            new = i
            return new
    else:
        if l%2==0:
            a = l/2
            b = a+1
            a = new[a]
            b = new[b]
            new = a+b
        else:
            a = int(l/2)
            new = new[x]
        return new

Ps. I wanna do this code my way. Just answer :slight_smile:


#7

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