What does 5 have to do with absolute value?
Following your logic:
def my_abs(value):
"""Returns absolute value without using abs function"""
if value <= 0:
return value * -1
return value * 1
print(my_abs(-3.5))
>> 3.5
print(my_abs(3.5))
>> 3.5
Other, shorter solutions also exist and can be seen in the other answers.
Answer from DeepSpace on Stack OverflowWhat does 5 have to do with absolute value?
Following your logic:
def my_abs(value):
"""Returns absolute value without using abs function"""
if value <= 0:
return value * -1
return value * 1
print(my_abs(-3.5))
>> 3.5
print(my_abs(3.5))
>> 3.5
Other, shorter solutions also exist and can be seen in the other answers.
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:
def my_abs(value):
return (value**2)**(0.5)
Videos
J, 2 bytes
**
Usage:
f =: **
f 9.3
9.3
f -9.3
9.3
Explanation:
This uses the * verb in both its monadic and dyadic forms. The monadic form returns -1 if it's given a negative number, 0 if it's given 0 and 1 if it's given a positive number. The dyadic form is just plain old multiplication. Putting them in a function literal turns them into a hook which gets evaluated like this: y * (*y).
GolfScript, 4 characters
I believe I win. ;)
Works with integer or decimal numbers of any length.
'-'/
Try it online
These programs do the same and are of equal length:
'-'-
'-'%
GolfScript (old version), 16 13
My first GS program! (that actually does something)
Doesn't work with decimal numbers because GolfScript doesn't have floating point.
~:$0<{0$-}$if
Hello everyone, I am brand new to python and I'm trying to do some exercise but for some reason I cannot solve this one. I need to write a function in which if i is equal or bigger than 0 it returns i as a string and if i is a negative number it returns i as a positive float number.
I've tried this so far:
def int_to_str_flt(i):
if i >= 0 :
return str(i)
else:
return abs(i)
If i is negative it returns a float number but it doesn't make it positive. What's wrong with this? How do I solve that?
{1e999: x, -1e999: -x}[x*1e999]
I'm serious. This works.
The 1e999 is interpreted as a float, but it overflows the available precision, so it's inf. But infinity can be positive or negative. By multiplying x with infinity, we can coerce it into one of two values based on its sign, without using a condition operator. Then we can select x or its negation from a lookup table.
It's equivalent to the following, but doesn't require the import:
from math import inf
{inf: x, -inf: -x}[x*inf]
If you consider the built-in classes (int, str, etc) to be built-in "functions". You could do something like the following
num.__class__(('%s' % num).lstrip('-'))
Convert the number to a string, strip the negative sign and then use the original numbers class to convert back
We have a little project where we are supposed to program absolute value without math.abs method. The question goes like this: "Suppose x and y are variables of type double. Write a program that reads in x and then sets y to the absolute value of x without calling the Math.abs() method."
Can someone help me with the code? What do you even code to accomplish this? Thank you in advance!!
I think you can probably figure this one out just with a hint.
What happens to negative numbers when they are multiplied by -1?
Note that you can check if numbers are less than zero using if and then do something about less than zero numbers.
If you still get stuck after thinking on that for a few minutes shoot me a pm.
Edit: as long as you don't ask me to just write out all the code for you.
You could just see if the number is less than 0 and then multiply it by -1
You can do it with the built-in abs() function:
absolute_val = abs(x)
Otherwise, without the built-in function, use math:
absolute_val = (x ** 2) ** 0.5
You wanted to calculate the absolute value using python. Here Im providing the code:
Python code function: abs(Number)
Python code example: abs(-100)
Python code example: abs(105-20)
Python code example: abs(100-200)
Output:

You can use
absandmapfunctions like thismyList = [2,3,-3,-2] print(list(map(abs, myList)))
Output
[2, 3, 3, 2]
Or you can use list comprehension like this
[abs(number) for number in myList]Or you can use list comprehension and a simple if else condition like this
[-number if number < 0 else number for number in myList]
A list comprehension would also work:
>>> lst = [2,3,-3,-2]
>>> [abs(x) for x in lst]
[2, 3, 3, 2]
>>>
The problem is with the loop you are using , Trying modifying it this way
def abs1(array):
for i in range(len(array)):
if array[i] < 0:
array[i] = array[i] * (-1)
print(array)
The reason is the loop you were previously using was just for accesing list elements but not giving you reference to change anything in list I solved it with using indexes on list.
Try :
import numpy as np
array= ...
np.abs(np.array(array))
numpy is very powerful and fast, learn to use it asap.
EDIT since the problem is how to do a function on each element of a list and wrap those results in a list of the same length :
Two solutions come to mind :
- hardcore python style :
[x if x<0 else -x for x in array]
the brackets say I want a list, inside I write the function and I say where to find the parameters to my function.
[abs(x) for x in array]
[f(x) for x in array] # for any defined f that can handle every element of array
- map(lambda x : f(x), array)
you create a mapping on the elements of array. To those elements, you apply lambda. lambda is a way to define a function locally, very locally.
list(map(lambda x : abs(x),array))
finally you make a list from the mapping, to retrieve the result. If you don't, it will stay as an abstract, the definition of a relation between array and something that is yet to be instantiated.
Hello,
I am not very familiar with python, my script is referencing an index of a notepad document. For example:
Value = lines[firsttag][9:21]
In this case, it is referencing a number in the notepad document which contains 12 characters. And I need the absolute value of it. Every time I put the “abs()” after the equal sign or even after the [firsttag]. My code errors out. Please advise.