What am I doing wrong?

def median(li):
    lis = sorted(li)
    if len(lis) % 2 != 0:
        return lis[(len(lis) / 2)]
        return (lis[len(lis) / 2] + lis[(len(lis) / 2) + 1]) / 2.0


should be - 1. I'll reserve my comments about implicit floats. That argument is getting tired.


Thanks! It worked. I guess I'm just really dumb. Oh well. Also I don't know what "implicit floats" are.


Now say the opposite, believe it, then move on. Delight in making mistakes; they are the best teachers.

(m + n) / 2.0

This is an implicit float. Now consider, when multiplying by one-half would we write it like this on paper:

m * (1 / 2.0)

? I think not. Teacher would be scratching their head.

m * (1 / 2)

tells it like it is. No head scratching. Rational numbers do not have decimal fractions.

There is no real harm is using implicit floats, except that from the above, we can see it does not read semantically. A fraction is easy to read. The unknown quantity could be either integer or float, we don't know just by looking. That would be the operand to cast one way or the other.

float(m) / 2

There is no head scratching there, either. The meaning is clear. The return value is explicitly a float.

Note: The above is no longer a rational number, since one of the operands has a decimal fraction. It is now a rational expression.


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