# Median ---Practice makes perfect

#1

This code works fine for a list whose total count is odd but for a list with even number of values , the answer is one unit less. For instance, i this example it gives me 4.5 instead of 5.5. Thank you for your patience

``````def median(inputlist):
sorted_i =sorted(inputlist)

if len(sorted_i)%2==0:# testing if number of  values is even
median = float(sorted_i[(len(sorted_i)/2)-1+(len(sorted_i)/2)])/2
else:
median = sorted_i[(len(sorted_i)/2)] # number of values is odd
return median
a = (2,0,6,9,5,7,8,2,1, 6)
print median(a)
print sorted(a)
print len(a)``````

Oops, try again. median([4, 5, 5, 4]) returned 2.5 instead of 4.5

4.5
[0, 1, 2, 2, 5, 6, 6, 7, 8, 9]
10
None

#2

here:

``median = float(sorted_i[(len(sorted_i)/2)-1+(len(sorted_i)/2)])/2``

you do a lot of complicated math to retrieve one value from the list. You need to retrieve left and right middle value, add them together and divide by two

#3

Hello and thank you for replying. Yes that was what I did or trying to do. In the above example my two middle numbers are 5 and 6 and should return 5,5 but I get 4.5. . In the line you highlighted I was trying to find the value occupied by the middle index positions. I have removed "float" but no joy. Sorry for being dumb

#4

``sorted_i``

then you have one set of square brackets, which will retrieve a value based on index:

``sorted_i[index]``

the index you use is:

``(len(sorted_i)/2)-1+(len(sorted_i)/2)``

this will calculate one index and retrieve the value at this index, what it should be instead:

``(yourList[leftIndex] + yourList[rightIndex]) / 2``

#5

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