Using Wing ide 3.3.5
How would I write a function my_abs(value) that returns the absolute value of its x, without using the built-in abs function in Python.
For example:
Test Result
print(my_abs(3.5)) 3.5
print(my_abs(-7.0)) 7.0
Using Wing ide 3.3.5
How would I write a function my_abs(value) that returns the absolute value of its x, without using the built-in abs function in Python.
For example:
Test Result
print(my_abs(3.5)) 3.5
print(my_abs(-7.0)) 7.0
A snarky answer would be to use the built-in __abs__()
function instead:
>>> print((-7.0).__abs__())
7.0
Here is a naïve one-liner (basically equivalent to @Nabin's answer):
def simple_abs(num):
return -num if num < 0 else num
However, it turns out that there is a bug, because
>>> -0.0 < 0
False
>>> simple_abs(-0.0)
-0.0 ← Buggy
>>> abs(-0.0)
0.0 ← Correct
It turns out that testing for negative zero in Python is hard to do. One possible test is str(-0.0) == '-0.0'
. Here's what @JasonS helped me come up with:
import math
def my_abs(num):
return -num if math.copysign(1, num) < 0 else num
Or, in longer, more readable form:
def my_abs(num):
if math.copysign(1, num) < 0:
return -num
else:
return num
A simple algorithm would be:
if number<0:
return number*-1
else:
return number
You have to check if the number is negative. Is so, then multiply it with -1 and return. Or you have to return the number without alteration.