15/15 Tell me what's wrong with my code


#1

def median(x):
sorted_x = sorted(x)
if len(sorted_x) % 2 == 0:
while len(sorted_x) > 2:
sorted_x.remove(sorted_x[0])
sorted_x.remove(sorted_x[-1])
return sum(sorted_x) / 2
else:
while len(sorted_x) > 1:
sorted_x.remove(sorted_x[0])
sorted_x.remove(sorted_x[-1])
return sorted_x[0]

When I put this into a text editor, it works. However, the same code gives me the following error in Codecademy: "median ([4, 5, 5, 4]) returned 4 instead of 4.5 "


#2

What version of Python are you using with your text editor?


#3

Version 3.6

Do you think that has something to do with it?


#4

That is an issue when you perform division. Codecademy uses Python version 2. See Python Syntax: Two Types of Division.

Correct that problem and see if there are any other issues.


#5

Thanks. Adding the periods after the numbers fixed it.


#6

Instead of adding decimal points to the data, change the 2 in the denominator here to 2.0

        return sum(sorted_x) / 2

… or, better yet, do this …

        return float(sum(sorted_x)) / 2

Then your median function could work with both int and float data.

EDITED April 13, 2018 to add the following …

The concept of repeatedly removing the first and last elements of the list until it contains only one or two elements works. However, be aware that the list.remove() method gets rid of the first occurrence of the value that you pass to it. Consider using del instead in order to literally delete the first and last element. This will do it …

            del sorted_x[0]
            del sorted_x[-1]

#7

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