Reputation: 4510
In a project of mine, I have to implement a function that adds or subtracts 1 based on the number's sign. Something like this,
def func(num):
if num > 0:
return num + 1
if num < 0:
return num - 1
But this seems like a unnecessarily long implementation for such a simple behavior. Is there an easier way to accomplish this. Maybe a one-liner ?
Upvotes: 2
Views: 83
Reputation: 166
def func(num):
if (num == 1):
return 2
elif (num == -1):
return -2
elif (num > 1):
return 1 + func(num-1)
else:
return -1 + func(num+1)
Can add an extra if check if 0 is an input to check for.
Upvotes: 0
Reputation: 91
Could use lambda to write a one line function.
a = lambda x: x+1 if x < 0 else x-1
Call it by doing this:
print(a(5)) # This would return 4 as the value.
Upvotes: 1
Reputation: 2581
You can use math module here:
>>> from math import copysign
>>> a = -1
>>> a += copysign(1,a)
>>> a
-2.0
>>> a = 3
>>> a += copysign(1,a)
>>> a
4.0
Numpy also provides a sign function
import numpy as np
a = 5
a += np.sign(a)
6
Upvotes: 3