Median. My code needs to be tweaked somewhere


#1


Practice Makes Perfect 15. median

My code seems to fail on lists with an even number of elements. I get the error message: Oops, try again. median([4, 5, 5, 4]) returned 5 instead of 4.5

I realise there may be ways to tidy up the code, but it looks as though it should work. It actually runs well in Python 3.


Replace this line with your code. Do not remove the backticks that are above or below this line.
def median(list):
    print(sorted(list))
    if len(list) %2 == 0:
        return (list[int(len(list)/2)-1]+list[int(len(list)/2)])/2
    else:
        return (list[int(len(list)/2)])


#2

You're creating a sorted copy of the list. And then you print that list. This new list is then discarded, both in Python2 and in Python3.


#6

Good point. I've changed my if/else statement so that it refers to the ordered list. Still no happy ending.

def median(list): #find the median of a list of numbers
a=sorted(list) #arrange the list into ascending order
print(a)
if len(a) %2 == 0: #the median can be the average of the middle two elements
return (a[int(len(a)/2)-1]+a[int(len(a)/2)])/2
else: #...or for an odd number of elements, the value is the middle element
return (a[int(len(a)/2)])

print(median([8,2,3,2,7,8,1,8,9,45,49,55,60,80]))


#7

It still returns good results in Python 3.


#8

I've changed the divided by 2 to a float i.e. divided by 2.0

def median(list): #FInd the median of a list of numbers
a=sorted(list) #arange the list into ascending order
if len(a) %2 == 0: #the median can be the average of the middle two elements
return (a[int(len(a)/2.0-1)]+a[int(len(a)/2.0)])/2
else: #...or for an odd number of elements, the value is the middle element
return (a[int(len(a)/2.0)])


#9

This works. I had to return a float.

def median(list):
a=sorted(list)
if len(a) %2 == 0:
return float(a[int(len(a)/2.0)-1]+a[int(len(a)/2.0)])/2
else:
return float(a[int(len(a)/2.0)])


#10

A post was split to a new topic: Why my code didn't pass