15/15 Find the median


#1


Hi I'm slightly confused as to why my code does not work,


def median(x):
    length = len(x) / 2 #find number in middle of list
    if length % 2 == 1: #IF list is odd
        return x[length]
    else:
        av = x[length] + x[length + 1] #add numbers in middle of list
        avtwo = av / 2 #divide by two to find middle
        return avtwo

        
    
    
    
median([2,3,4,4,3])


What am i missing here?


#2

That took me longer then excepted. You want to check the list has a odd or even number items right? So you do that here:

if length % 2 == 1:

however, your length variable is the length of the list divided by 2 (and since those are both integers, the number gets truncated), see the line where you defined the length variable:

length = len(x) / 2

you should check the length of the list instead, if you need more help let me know


#3

Firstly thank you for taking time to help me.
I'm not quite sure what you mean because I'm getting the correct Median for odd numbers.
I've modified my code to

def median(x):
    length = len(x) / 2#find number in middle of list
   
    if length % 2 == 1: #IF list is odd
        return x[length]
    else:
        av = x[length] + x[length - 1] #add numbers in middle of list
        avtwo = av / 2.0 #divide by two to find middle
        return avtwo

    
print median([3,4,5])

but receive the error
Oops, try again median([4, 5, 5, 4]) returned 5.0 instead of 4.5

Thanks again


#4

Well, the first point i was going to make was that length variable in this line:

if length % 2 == 1:

is not the length of your list. It is the length of your list divided by two and then truncated, but for some reason it works now...

You should also sort the list, from the instructions:
For example, the median of the sequence [7,3,1,4] is 3.5, since the middle elements after sorting the list are 3 and 4 and (3 + 4) / (2.0) is 3.5

Now, lets look at your 4,5,5,4 list, after you sort, it should be 4,4,5,5 and then middle two numbers (4 and 5) should be added (9) and then divided by two. a integer (a non decimal number) divided by a integer, is a integer (the number get truncated, everything after the decimal gets thrown out of the window.

So 9 / 2 = 4. Not 4.5

Two solutions: cast it to a float using float() function, or divide by a float (a decimal number)

From google:
In mathematics and computer science, truncation is limiting the number of digits right of the decimal point


#5

Thank you for taking your time to explain, I solved it following your advice. :slightly_smiling: