[英]How to add a to the absolute value of b without call abs
我在定义函数时遇到了一些问题。 我试图在不调用ab的情况下将a添加到b的绝对值
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)
您不需要为此导入add()
。
你为什么不干脆做
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
您正在寻找的解决方案如下所示,因为您沉迷于“负数”的概念而被忽略了:
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)
请注意,用于调用函数的括号仅在最后一行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.