Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return 1 or -1 if number is positive or negative (including 0)?

Tags:

python

math

Can I ask how to achieve this in Python:

Input: I = [10,-22,0]

Output: O = [1,-1,-1]

I was thinking O=I/abs(I)

But how to deal with zero?

like image 586
lanselibai Avatar asked Dec 18 '22 19:12

lanselibai


1 Answers

The following should do what you want:

>>> I = [10,-22,0]
>>> O = [1 if v > 0 else -1 for v in I]
>>> O
[1, -1, -1]
>>> 

If you want to use map with a lambda, you can do:

>>> O = map(lambda v: 1 if v > 0 else -1, I)
>>> O
[1, -1, -1]
>>> 
like image 96
Tom Karzes Avatar answered Dec 21 '22 11:12

Tom Karzes