# 15. Practice makes perfect: Median

#1

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

``````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

else:
mid_index = int(mid_index+0.5)
total = numbers[mid_index]

#2

This offset needs to be minus 1.

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

#3

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

#4

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.

#5

Aside

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.

#6

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

#7

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

#8

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