15. median


def median (lst):
    slst = sorted(lst)
    length = len(slst)
    if length % 2 == 0:
        return (slst[length / 2] + slst[(length / 2) - 1 ]) / 2.0
        # if 4 obj in slst, returns slst[2] + slst[1] / 2
        return slst[(length + 1 / 2) - 1]
        # if 5 obj in slst, returns slst[2]

Error: median([6, 8, 12, 2, 23]) returned 23 instead of 8

I don't have any idea of what's wrong...


Do you know how to compute the median for the list the error message mentions?

If so, start comparing what your code does to that. Use prints to print out what your code does and compare. Split up long expressions if you're doing multiple things at once that you can't print. Find out exactly which operation(s) isn't doing what you think it should by printing out what you've got before and after each one (or rather, start checking somewhere in the middle of the process and then go earlier or later depending on whether it's wrong at that point)

Otherwise, figure out how to compute the median, wikipedia is a good place to start but there are probably a good couple of hundred math education sites if you google for that which also explain it


Yep, I did it the way you suggested and apparently (fortunately?), the else statement was the one with errors.

Turns out I had a missing () within the length + 1 / 2, resulting in 1 getting divided by 2 first.

Thanks a lot for your help! :slight_smile:


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