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.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With