Median problem


why this code on a list [4,5,5,4] return 5 and how can i fix it?


Replace this line with your code.
def median(kist):

nl = sorted(kist)
if len(nl)%2 == 0 :

   sbu = float(nl[len(nl)/2] + nl[(len(nl)/2)+1])/2.0
   return sbu

return nl[len(nl)/2]


I'm assuming that when manually computing the median for that you'll get a result of 4.5

To debug this you'll need to compare what your code does to what you want it to do. Identify where it is doing something differently.

To that end, you can split up your expression in smaller parts and assign them to variables and print them out to see if they refer to the values you want them to refer to.

Note that it's important to keep details intact in code, subtle changes can make a lot of difference so make sure that it shows up correctly when you share it with other people (and at all times really, it won't do to corrupt it)


this is my code in copy paste and i cannot find any false but it's still telling me that is wrong


Look at your post. Is that what your code really looks like? If you were to copy from your post and try to run that, will it behave the same way? You have to take care that it is exactly the same.

Have you printed out what each part of that expression evaluates to for [4, 5, 5, 4]? And did you compare them to what you wanted to happen? Otherwise, that's what you'll need to do to find where it's gone wrong.


ok thank you very much for your help


you just change that line to:
float(nl[len(nl)/2] + nl[(len(nl)/2)-1])/2.0
note that -1 not +1