Why is my median incorrect?


#1

Question

Why is my median incorrect?

Answer

Finding the median of a list of numbers can be especially difficult if it’s an even number of numbers. To ensure that you’re actually working with the values you think you are, it can be very helpful to print them all out at each step. For example, when you sort your list, print your_sorted_list to see if it worked. When you calculate the midpoint, print your_midpoint to see if it’s the value at the middle index, or if it’s the middle index.
Half the battle is knowing what you’re working with at each step of the way. There are so many approaches to this particular problem that it’s not very meaningful to try and guess what could be wrong in your particular implementation. However, it will always be helpful to print your code out in steps, as that’s a major part of debugging!
Once you know what your values actually store, then you can proceed to make necessary changes with everything we’ve learned so far.


FAQ: Learn Python - Practice Makes Perfect - median
#2

Because the interface’s answer is wrong. The solution prints the median where 4 and 5 are in the middle, in which the answer is 4.5. However, the interface inputs 5 and 5 in the middle, but still thinks the answer is 4.5, even though it would just be 5 (5 + 5 = 10 / 2 = 5).


#3

The answer is 4.5 because they say to sort the list. This changes [4, 5, 5, 4] to [4, 4, 5, 5].


#4

I did it absolutely correct and yet it says my coding is incorrect and returns 4.0 when it actually returns 4.5 as intended.

def median(numbers):
numbers.sort()
middle = len(numbers) // 2
if len(numbers) % 2 == 0:
median = float((numbers[middle] + numbers[middle - 1]) / 2)
else:
median = float(numbers[middle])
return median

print(median([102, 56, 34, 99, 89, 101, 10, 54]))


#5

when the division involves two integers ( 9 / 2 ) python will round down to the nearest integer, casting to float after the division means the damage is already done


#6

Actually the division prior only matters for ODD numbers because if it’s even it divides into an integer anyway. Take your example, if you have a list that is 9 long, divided by two is 4.5, rounded down is 4, yet when it’s an odd amount of numbers the middle number is actually place 5 in the list but when I’m displaying the number I am using THE INDEX, which starts as 0 and that means the middle number is the FOURTH index, which translates to the FIFTH number in the list, since I return the 4th INDEX, which is the FIFTH number.

I’m using Pycharm, the code I posted works perfectly in PyCharm, so as I say, something is wrong with CodeAcadaemy in this instance.


#7

that is not my example, i was doing the math of this line:

median = float((numbers[middle] + numbers[middle - 1]) / 2)

based of the list you where struggling with ([4, 5, 5, 4])

no, python made breaking changes moving forward, including in division behavior. so you are experiencing an additional obstacle because of these breaking changes.


#8

Sorry but you’re wrong, check and see the exact same code for yourself functioning exactly as intended
4, 5, 5, 4 length is 4.
numbers.sort()
middle = len(numbers) // 2 # In this case it is 2.
if len(numbers) % 2 == 0: # In this case it is
median = float(numbers[middle] + numbers[middle = 1]) / 2)

In this instance I am storing as a float the equation of (5 + 4) / 2 which is 4.5, being stored as a float, in median and returning it, which is 4.5


#9

in python3, you are right, the output is 4.5, but in python2 (which codecademy uses) the division behavior works different:

which i have attempted to explain


#10

I’m not struggling in the slightest as you can clearly see unless you’re saying my PyCharm is magically broken and not functioning as intended, I type cast the equation as type float which will store the equation, as a float in to the variable called median.


#11

i am not saying pycharm is broken, i just say that there are two major python versions which are not compatible. You can’t expect code from python2 to work flawlessly in python3 and vice versa


#12

Thank you for taking the time and baring with me and i am very sorry if I came across in a negative way towards you at all, it’s my bad for not understanding properly and I should have thought better about my responds and what it is you’re explaining.

Keep up the excellent work you’re doing here and in future I’ll do better to articulate, respond and understand what I’m being told.


#13

apology accepted, i understand, programming can be frustrating :slight_smile:

although that is true, the response was very much not where you where expecting, so then it can be difficult to accept

i will, thank you :slight_smile:

Given your response, i assume you solved the issue? :slight_smile:

PS, i also wished the codecademy course was python3, but i don’t have a say in these things. Furthermore, understanding some of the differences can make you better at python and maybe even programming in general.


#14

Hello - I’ve been working on this problem for a while and I get an error that says my median function returns none. Specifically: “median([1]) returned None, did you remember to return the result?”

I can’t figure out why because I definitely am returning. Could someone please take a look and offer some advice?

Thank you.

def median(lst):
  lst = [] 
  sortedlst = sorted(lst) #sort input list of numbers
  middle = len(sortedlst) / 2 #find middle position of sorted list
  if len(sortedlst) == 1: #in the case that there's only one number
    return lst
  elif len(sortedlst) > 1 and len(sortedlst) % 2 == 0: #if more than one & even amount of numbers
    avg = float(sortedlst[middle] + sortedlst[middle+1] / 2)
    return avg
  elif len(sortedlst) > 1 and len(sortedlst) % 2 != 0: #if odd amount of numbers
    roundmid = round(middle) #would have to round the middle position if odd amount
    return sortedlst[roundmid]

print median([1,1,2]) #returns none???

#15

you understand how function parameters (lst in your code) and arguments ([1, 1, 2] in your code) work? Because you overwrote the parameter with an empty list.


#16

Thanks! Had to go back and review the lists chapter for sure!


#17

Actually I’ve been tinkering around with this and running into a different issue. Below is a sample code I tested in Python IDLE.

I now get an error in Codecademy that says “median([4, 5, 5, 4]) returned 4.0 instead of 4.5”

But IDLE returns test2 as 4.5. I suspect this has something to do with the floor division differences in versions 2 and 3, although I can’t seem to pinpoint where exactly I should change it so that Codecademy accepts my code. Any suggestions or recommendations?

def median(lst):
  sortedlst = sorted(lst) #sort input list of numbers
  middle = len(sortedlst) // 2 #find middle position of sorted list
  if len(sortedlst) == 1: #in the case that there's only one number
    return sortedlst[0]
  elif len(sortedlst) > 1 and len(sortedlst) % 2 == 0: #if more than one & even amount of numbers
    avg = (sortedlst[middle] + sortedlst[middle-1]) / 2
    return float(avg)
  elif len(sortedlst) > 1 and len(sortedlst) % 2 != 0: #if odd amount of numbers
    roundmid = round(middle) #would have to round the middle position if odd amount
    return sortedlst[roundmid]

test = [1, 45, 9, 91, 8, 8]

print (median(test))

test2 = [4, 5, 5, 4]
print (median(test2))


#18

have you googled how the division behavior works in the different major python versions? You don’t use the division operator (/( a lot (only once in fact), so there is only line where the problem can be?

i didn’t count // because its floor division