Median


#1



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


I keep getting the error: "2.0 is not in the list" for median[4,5,5,4]. I have no idea why- nothing I do should return 2.0 at all.


def median(h):
    sort = sorted(h)
    if len(sort) % 2 != 0:
        q = sort.index(int((len(sort)+1)/2))
        return sort[q]
    if len(sort) % 2 == 0:
        n = (len(sort)/2.0)
        m = (len(sort)/2)-1)
        x = sort.index(n)
        y = sort.index(m)
        return float(((sort[x]+sort[y])/2))


#2

First off, a good practice is to name our variables carefully. Naming after the operation is something that may end up confusing a reader, and one's self.

def median(sample):
    sorted_sample = sorted(sample)

That is something the reader can understand at any point in the code following.

Consider the complexity of your code. Is all that processing really necessary?


What is the median? It is the middle value or central mean of a sorted sample space (a list of data). When the list length is odd, it is the middle element, and when even it is the average of the middle two elements.

By this definition we can begin to assemble the necessary data components for our program.

# the sorted sample
# the length of the sample
# the middle of the sample

sorted_sample = sorted_sample
n = len(sample)
m = int(n / 2)

That is all the data we need, and no more real processing involved. We have the index of the middle element for an odd length list, and the higher order pair index for the even length list.

For this illustration, let x = sorted_sample

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

#3

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