15:15 Think my answer is wrong but codeacademy says it's right


#1

def median(raw):
new=sorted(raw)
if len(new)%2==1:
return new[int(len(new)/2+0.5)]
else:
return 0.5*new[len(new)/2]+0.5*new[len(new)/2-1]

So this is my code, the bit im not sure about is the 4th line, where i've written "+0.5", i swear it should be "-0.5"?
In a list of 5 numbers you want the third, i.e the one at index 2? So len(new)/2-0.5 will give 5/2-0.5 which equals 2...

Codeacademy is accepting the +0.5 which implies index 3 but not the -0.5 version which implies index 2.

Not sure what's wrong here unless my understanding of len() is wrong?


#2

When you post code, ensure that it is intact in your post.

Regardless of what's going down in there, I strongly suggest avoiding floats because they are not exact and you are doing something that is exact.

Dividing two integers in Python 2 results in an integer, which means that your +0.5 has no effect at all

In Python 3, division between integers results in a float, so you might see a different outcome there.

But again, avoid floats in all cases unless you need approximations of numbers, because that is what they are, and they are not fit for anything else.

In some cases floats are capable of exact operations, but there are going to be a whole bunch of if's and but's around it that you have to keep track of and if you're doing exact operations you have no need for floats anyway.