Problem with Median


#1

I wrote my code for the Median - Practice makes perfect section, and kept getting errors in the editor and messages saying that I was returning the wrong information from the class. When I run the code directly in Python 3 it works without any problems. Could you tell what I’m doing wrong with the following code?

def median(x):
    list = sorted(x)

    if len(list) % 2 == 0:
        first = round(len(list)/2)
        second = first - 1
        return ((list[first] + list[second]) / 2)
    else:
        dig = round(len(list)/2)
        return list[dig]
    
print(median([5,24,2,6,9,1]))

Thank you


#2

Even if it appears to work, it is never a good practice to name variables the same as the class name. list is a reserved word, and name of a built-in function.

The indentation of else looks to be off.


#3

Thanks. Didn’t realize list was a reserve word.

I had to manually add the indents into the forum editor, as it removed them when I just copied/pasted the code into it.


#4

Select the code then click the </> button in the tool bar.

Notice that it is highlighted in your edited OP?


#5

Great tip. Thank you


#6

Let’s pretend your variable is sample

return (sample[first] + sample[second]) / 2

Python 2 will return an integer, so we need to declare the sum as a float…

 return float(sample[first] + sample[second]) / 2

#7

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