Negative integers
Dan Stromberg
dstromberglists at gmail.com
Wed Aug 20 18:00:58 EDT 2008
On Wed, 20 Aug 2008 14:38:11 -0700, johnewing wrote:
> I am trying to figure out how to test if two numbers are of the same
> sign (both positive or both negative). I have tried
>
> abs(x) / x == abs(y) / y
>
> but that fails when one of the numbers is 0. I'm sure that there is an
> easy way to do this. Any suggestions?
>
> Thanks
Don't resort to inline tricks too soon. Write your program in a very
straightforward way (perhaps paying attention to algorithm choice or a
functional style), and only start optimizing if it's too slow. And if it
is too slow, you probably should look at pyrex or similar before
resorting to unusual python code.
Part of writing straightforwardly, means having a function or object that
encapsulates each decision the program makes - so that if that decision
later needs to be changed, it can be changed in one place.
I've been frequenting comp.unix.shell lately, and the group is plagued
with weird little tricks - EG, using : as an alias for true, 1 as an
alias for print, etc. I'd rather not see comp.lang.python turned into
that sort of group. (That said, I program in bash frequently - by choice)
$ cat /tmp/sign
#!/usr/bin/env python
def sign(x):
return cmp(x,0)
print sign(-5)
print sign(0)
print sign(33)
if sign(-5) == sign(-2):
print 'Same sign'
More information about the Python-list
mailing list