recreation of absolute value finder not working as intended

38 Views Asked by At

I have scripted a code that gives the absolute value of any number here is the code:

def absolute(num):
    numb = str(num)
    numb.replace("-","")
    numb = int(numb)
    return numb

When used it gives an output of the same integer:

>>> absolute(-12)
-12

When I did the function step by step I found out that there is the problem in int function where the string "12" gets converted into -12

I know other methods of making this but if you can explain why this happens and that would be better as I can understand what happens.

Thanks!

2

There are 2 best solutions below

2
On BEST ANSWER

Here you don't assign .replace return value back to the variable:

def absolute(num):
    numb = str(num)
    numb = numb.replace("-","")
    numb = int(numb)
    return numb

In short:

def absolute(num):
    return int(str(num).replace('-',''))

And one bizarre thing, don't you know about abs() LOL?

abs(-12)
0
On
absolute = lambda x : int(str(x).replace('-',''))
absolute(-5)

I shortened the answer someone else gave you. Its a little slow when I time it but I'm sure it should work fine. :)