How to add a to the absolute value of b without call abs
I'm having a little problem defining a function. I'm trying to add a to the absolute value of b without calling开发者_运维技巧 abs
from operator import add, sub
def a_plus_absolute_b(a, b):
"""Return a+abs(b), but without calling abs."""
if b < 0:
op = add(a, (b * -1))
else:
op = add(a, b)
return op(a, b)
You don't need to import add()
for this.
Why don't you simply do
def a_plus_absolute_b(a, b):
"""Return a+abs(b), but without calling abs."""
if b < 0:
result = a - b
else:
result = a + b
return result
The solution you're looking for, which you're overlooking because you're obsessed with the idea of "negative", is as follows:
from operator import add, sub
def a_plus_absolute_b(a, b):
"""Return a+abs(b), but without calling abs."""
if b < 0:
op = sub
else:
op = add
return op(a, b)
Note how the parens, used to call a function, are only in the last line.
精彩评论