Median guide


I am stuck at median , I have been trying to look into the forums but am stuck and need guide with my code

Oops, try again. median([6, 8, 12, 2, 23]) returned 7.0 instead of 8

def median(lst):
    if length%2==0:
        median_even =(lsd[length]+lsd[length-1])/2.0
        return median_even
        median_odd = lsd[length]
        return median_odd


Say I have a list length of 5. length = 5 / 2 -> 2 because this is integer division meaning whatever float becomes integer. In this case, 5/2 should be 2.5 right? But in integers, it is 2 since 2 is the integer part in 2.5. Therefore, length is actually 2 and 2 is an EVEN number for a list of 5 items.

I suggest you take another look at your length variable definition.


Naming variables does have one unwritten rule... Make them mean what they represent.

length = len(lsd) / 2

The variable is not truthful. What it represents is not length, but the middle of the list. Because it is going to be used as an index it must be an integer. Python 2 returns an integer when both numerator and denominator are integers (integer division). We could write this more explicitly for the sake of the reader.

middle = int(len(lsd) / 2)

This is also compatible with Python 3, which makes it mandatory since all rationals return as floats.

Python 2 requires that we explicitly (or implicitly with 2.0) declare our floats. For the sake of the reader, don't write counting numbers as floats. Leave them as integers. The value that could feasibly be a float is the one to declare.

return float(x[m - 1] + x[m]) / 2

On the whole, too many variables can really muddy the waters, despite any belief it will make it easier to understand the code. It just makes for harder debugging (and reading). Pick the working variables you need, and if necessary, re-use them.


def median(lst):
if length%2==0:
median_even = (lst[length/2]+lst[(length/2)-1])/2.0
return median_even
print median_eve
median_odd = lst[length/2]
return median_odd
print median_odd


Thank you guys for advising me, I could finally solve it. :grinning:


Be sure to come back during your review of the unit and try to refactor this into something simpler.


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