15. Practice makes perfect: Median



When I run the code, the following message pops up: median([6, 8, 12, 2, 23]) returned 12 instead of 8

Can someone help please?

def median(numbers):
    sort = sorted(numbers)
    length = len(numbers)
    mid_index = length/2
    total = 0
    if length % 2 == 0:
        mid_1 = mid_index
        mid_2 = mid_index + 1
        total = numbers[mid_1] + numbers[mid_2]
        total = total/2.0
        return total
        mid_index = int(mid_index+0.5)
        total = numbers[mid_index]
        return total


This offset needs to be minus 1.

No need to go to all that trouble. Just make it an integer without the adjusment.


you have'nt sorted the array properly
you should do
numbers = numbers.sort()
instead of sort = sorted(numbers)..


Beg to differ. It is you who hasn't sorted the numbers properly.

copy = sorted(sample)    # sample is unaffected, just copied in sorted order

sample.sort()            # sample is directly affected by the sort

We've spotted the errors, and it is nothing to do with sorting, but with positioning the index(es). Both odd and even length lists, once sorted were still returning a value higher than it should have been.



On sorting the inputs, we have two considerations. Does the data structure exist outside of the function, or is it a directly inputed argument.

sample_space = [ ... ]                     # data structure exists

sample_median = median(sample_space)

sample_median = median([6, 8, 12, 2, 23])  # direct input

Given the first consideration, we would be unwise to sort in place since that would irrevocably alter the orginal sample, something we might not want to do, and that could have far reaching consequences if that sample is also an index.

In that case, we use a copy inside the function, and leave the sample alone.

In the case of the second example, we don't need a copy because nothing exists outside of the function that can be altered. The argument disappears when the function ends.

In that case, in place sort will be a relevant approach.


Thanks.. I used your tip and fixed my code.


Yes, I was mistakenly addressing the unsorted list for the values. Figured out my mistake. Thank you though.


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