Function in python that outputs either -1 or 0 or 1

Question:

Is there like a (modified) round function where the output would be either -1,0,1 depending on to what number is the input the closest? E.g. 0 => 0, -2154 => -1, 10 => 1

Currently I am using normal if else statements:

if i == 0:
    return 0
elif i > 0: 
    return 1
else:
    return -1

But is there any way how I can make this a one-line code? By for instance using some modified round function.

Asked By: Sam333

||

Answers:

You can use numpy.sign()

import numpy as np

print(np.sign(1.2))
print(np.sign(-3.4))
print(np.sign(0))

output:

1.0
-1.0
0

Without any imports:

def sign(i):
    return (i>0) - (i<0)
    
print(sign(1))
print(sign(-3))
print(sign(0))

output:

1
-1
0
Answered By: joostblack

As the other answer commented, you can do it easily by using the numpy.sign() method, that directly returns your desired result.

However, you can do it directly using the built-in math function and the method copysign(x, y), which copies the sign of the second value to the first. By setting the first value as a boolean it will be interpreted as 0 if the original value is 0, and 1 otherwise. Then we copy the sign of value, which will transform the 1 into -1 or leave it positive.

from math import copysign

values = [1, 200, 0, -3, 45, -15]

for value in values:
    print(int(copysign(bool(value), value)))

which outputs:

1
1
0
-1
1
-1
Answered By: josepdecid

Here is a one-liner function using plain vanilla python and no imports. It can hardly get simpler than this.

def f(i):
    return -1 if i < 0 else int(bool(i))


In [5]: f(0)
Out[5]: 0

In [6]: f(1)
Out[6]: 1

In [7]: f(-5)
Out[7]: -1
Answered By: alec_djinn