Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 919
Sam333 Avatar asked Jun 22 '26 19:06

Sam333


2 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
like image 158
joostblack Avatar answered Jun 24 '26 07:06

joostblack


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
like image 25
alec_djinn Avatar answered Jun 24 '26 09:06

alec_djinn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!