# Median

#1

On the same note as the median function throwing errors, I've written the following code and tested it in iPython. It works just fine there, specifically on the list [4,5,5,4], returning 4.5. However, in this console, it tells me that it's returning 4 instead of 4.5 for that list. I literally copied and %pasted the code from the Codecademy console into iPython, and there it works fine. Any ideas?

Code:
def median(lst):
lst = sorted(lst)
if len(lst) % 2 == 0:
return (lst[int(len(lst)/2 - 1)] + lst[int(len(lst) / 2)]) / 2
else:
return lst[int((len(lst) - 1 ) / 2)]

Note: the post doesn't save my indentations, but they are correct.

Median
#2

in python2 a integer divided by a integer gives a integer (integer is non decimal number), however, in python3 this behavior was changed. Now a integer/integer now can give a float, so this line:

``return (lst[int(len(lst)/2 - 1)] + lst[int(len(lst) / 2)]) / 2``

works in python3, in python2 you would need to divide by a float (for example 2.0), or use the `float()` function

#3

I have a question, why you put "lst" before "int" in "lst[int(len(lst)/2 -1)]. What's the purpose?

#4

I often find that when I copy and paste something from another app (i.e. Notepad ++) it doesn't work. However, if I completely retype the same code in Codeacademy it does work. I think this is just a formatting error (with indents turning into spaces or something) but I'm not sure.

One thing that I notice about your code is that you immediately sort lst. I would suggest creating an entirely new list to put sorted(lst) in. For example, you could write: new_list = sorted(lst)

On line 4, I think you need another set of parentheses to separate the 2 and 1. Right now, I would read that as lst[int(len(lst)/(2-1))] , but I think you mean lst[int((len(lst)/2) - 1)]. The way this is read might vary from iPython to Codeacademy, so putting in parentheses is probably a good idea.

If you can't figure it out still, here's what I did:

def median(n):
....x = sorted(n)
....a = len(x) / 2.0
....if len(n) == 1:
........return x[0]
....elif len(x) % 2 == 0:
........return (x[int(a - 1)] + x[int(a)]) / 2.0
....elif len(x) % 2 == 1:
........return x[int(a - 0.5)]

the ........s are just for indents

#5

That was it! Thank you. Still not quite clear on all the differences between the two versions of Python, I appreciate the comment.

#6

python2:

``````9 / 2 = 4
9 / 2.0 = 4.5``````

python3:

``````9 / 2 = 4.5
9 // 2 = 4``````

little change in the behavior of python.

#7

A post was split to a new topic: Median