Median


#1



https://www.codecademy.com/courses/python-intermediate-en-rCQKw/2/5?curriculum_id=4f89dab3d788890003000096


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


Whether I change the modulo condition to 0 or 1, I still receive 4.5 for the above error. I think that means that that elif statement is never executing? I'm lost at this point, especially since this runs fine in IDLE on my laptop.


def median(lst):
    srt=sorted(lst) #sort list
    length=len(srt)-1
    if length==0: #check for single entry list
        return lst[0]
    elif length%2==0: #check if list is an odd number of entries
        return srt[int(length/2)+1] #return middle number
    else:
        lower=int(length/2) #define index for number below middle
        upper=int(length/2)+1 #define index for number above middle
        return (srt[lower]+srt[upper])/2 #average above indexed numbers


#2

Hi @koreanviking,

Check the index you have calculated here ...

    return srt[int(length/2)+1] #return middle number

Consider guaranteeing float division here, in case lst contains only int objects ...

    return (srt[lower]+srt[upper])/2 #average above indexed numbers

#3

I'm not using that for division so much as index numbers- using int assures I'll always return a position in the list I'm working with. For example, if I used float on a list with an odd number of entries, it would try to call srt[3.5] since length=len(srt)-1. Unless I REALLY don't understand what I'm doing here, and that's a distinct possibility.


#4

Let's consider, as an example, a sorted list that has five items in it. Their indexes would range from 0 through 4, inclusive. The middle item would have an index of 2, and that one would hold the median.

With an odd number of items in a list, the expression you are using to compute the index of the middle item is ...

int(length/2)+1

... with length equal to 4, since you computed it as follows ...

    length=len(srt)-1

Performing the math, the index works out to be 3 instead of the correct value of 2.

Your statement should be changed to ...

    return srt[int(length/2)] #return middle number

That would calculate the correct index, 2, and would also work correctly for other lists with an odd number of items.

In the case of a list with an even number of items, you need to perform float division when you divide by 2. To guarantee float division, you can convert the numerator to float prior to the division, as follows ...

    return float(srt[lower]+srt[upper])/2 #average above indexed numbers

#5

Thank you so much! I don't know how I got that so backwards in my head, but I'm really grateful for the help


#6