How To Get Absolute Value Without 'abs' Function?
def my_abs(value): '''Returns absolute value without using abs function''' if value < 5 : print(value * 1) else: print(value * -1) print(my_abs(3.5)) th
Solution 1:
What does 5
have to do with absolute value?
Following your logic:
defmy_abs(value):
"""Returns absolute value without using abs function"""if value <= 0:
return value * -1return value * 1print(my_abs(-3.5))
>> 3.5print(my_abs(3.5))
>> 3.5
Other, shorter solutions also exist and can be seen in the other answers.
Solution 2:
The solutions so far don't take into account signed zeros. In all of them, an input of either 0.0 or -0.0 will result in -0.0.
Here is a simple and (as far as I see) correct solution:
defmy_abs(value):
return (value**2)**(0.5)
Solution 3:
A simple solution for rational numbers would be
def my_abs(value):
if value<0:
return -value
return value
Solution 4:
Why do you want to check if value < 5
?
Anyways, to replicate the abs function:
defmy_abs(value):
return value if value >=0else -1 * value
Solution 5:
num = float(input("Enter any number: "))
if num < 0 :
print("Here's the absolute value: ", num*-1)
elif num == 0 :
print("Here's the absolute value: 0")
elif num > 0 :
print("Here's the absolute value: ", num)
Post a Comment for "How To Get Absolute Value Without 'abs' Function?"