# What am I doing wrong? Median

#1

Hello!
I have another question on the median assignment.
The error I get is "median([4, 5, 5, 4]) returned 5 instead of 4.5"
Here’s my code: I assume the mistake is in line 7, where I calculate the average
’’‘
def median(my_list):
sorted_sequence= sorted(my_list)
if len(my_list)%2==0:
while len(my_list)>2:
del my_list[0]
del my_list[-1]
average=(my_list[0]+my_list[1])/2
return average
else:
while len(my_list)>1:
del my_list[0]
del my_list[-1]
return my_list[0]
’’'
Thank you!

#2

sorry, here’s my code again:

``````def median(my_list):
sorted_sequence= sorted(my_list)
if len(my_list)%2==0:
while len(my_list)>2:
del my_list[0]
del my_list[-1]
average=(my_list[0]+my_list[1])/2
return average
else:
while len(my_list)>1:
del my_list[0]
del my_list[-1]
return my_list[0]
``````

#3

Python two will return an integer.

``````average = float( ... ) / 2
``````

will return a float.

#4

Hmm… Thank you, but it still returns the same error, except that now it says 5.0 instead of 5

``````def median(my_list):
sorted_sequence= sorted(my_list)
if len(my_list)%2==0:
while len(my_list)>2:
del my_list[0]
del my_list[-1]
average= float(my_list[0]+my_list[1]))2
return average
else:
while len(my_list)>1:
del my_list[0]
del my_list[-1]
return my_list[0]
``````

#5

Never mind, I found the mistake! I was using the original list instead of the “sorted_sequence”.
Thank you for your help, though.

#6
``````def median(given_list):
my_list= sorted(given_list)
if len(my_list)%2==0:
while len(my_list)>2:
del my_list[0]
del my_list[-1]
return float(my_list[0]+my_list[1])/2
else:
while len(my_list)>1:
del my_list[0]
del my_list[-1]
return my_list[0]
``````

#7

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