cmp() on integers - is there guarantee of returning only +-1 or 0?

Christoph Zwerschke cito at online.de
Mon Mar 20 07:36:23 EST 2006


Alex Martelli wrote:
> <skip at pobox.com> wrote:
>> Why not
>>
>>     def sign(n):
>>         return n and n/abs(n) or 0
> 
> If you assume n is a number, the 'or 0' appears redundant (if you don't
> so assume, then the abs(n) and the division are doubtful;-).

Without the 'or 0' it is also more consistent with the behavior of your 
function that the sign of a float is also a float.

One issue is that division should be normally avoided because it is a 
costly operation and can lead to rounding errors. Maybe performance is 
is not a problem for ints and floats, but if you are planning to use the 
function on long ints, I would consider using something like:

def sign(x): return x>0 and 1 or x<0 and -1 or 0

def sign(x): return (x>0)-(x<0)

-- Christoph



More information about the Python-list mailing list