# Median (15)

#1

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

How can I solve this error message? I don't have a clue

def median(lst_numbers):
sort_list = sorted(lst_numbers)
if len(sort_list) == 1:
median = sort_list[0]
return median

elif len(lst_numbers)%2 == 0:
median = ((sort_list[len(sort_list)/2])+(sort_list[((len(sort_list)/2))+1]))/2
return median

else:
middle_num = (len(sort_list)/2) + 0.5
median = sort_list[middle_num]
return median

return median

#2

First of all I think your code is a tad bit more complicated than it should be and to write efficient, clean code is always good practice for a programmer.

#3

Hi,

You can find answer in a duplicate post here:

medians

#4

def median(x):
y=list(x)
y=sorted(y)
if len(y)%2==0:
med=float((y[(int((len(y)+1)/2))-1]+y[int(round((len(y)+1)/2))-1])/2)
else:
med=y[int(round(len(x)/2))]
return med

Hi please tell me where I am getting this wrong.
Error:median([4, 5, 5, 4]) returned 4.0 instead of 4.5

#5

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