开发者

How to add a to the absolute value of b without call abs

开发者 https://www.devze.com 2023-04-02 04:41 出处:网络
I\'m having a little problem defining a function. I\'m trying to add a to the absolute value of b without calling开发者_运维技巧 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消