Problem 1: A Add Abs B (100pts)
Problem
Fill in the blanks in the following function for adding \(a\) with the absolute value of \(b\), without calling
abs. You may not modify any of the provided code other than the two blanks.
填写以下函数中的空格,以计算 \(a\) 加上 \(b\) 的绝对值,且不得调用 abs 函数。除了两个空格之外,您不得修改任何提供的代码。
from operator import add, sub, mul, neg
def a_add_abs_b(a, b):
r"""Return `a + abs(b)`, but without calling abs.
>>> a_add_abs_b(2, 3)
5
>>> a_add_abs_b(2, -3)
5
>>> # a check to ensure that the return statement remains unchanged!
>>> import inspect, re
>>> re.findall(r'^\s*(return .*)', inspect.getsource(a_add_abs_b), re.M)
['return h(a, b)']
"""
if b >= 0:
h = _____
else:
h = _____
return h(a, b)
Hints
Hint: You may want to use add, sub, mul and/or neg that imported from operator.
Here is the documentation of these operators.
-
您可能需要使用从
operator模块导入的add、sub、mul、neg函数。 -
这些运算符的文档:operator。
-
注意
h是一个函数,所以填空的地方也要填一个函数。
Solutions
当 b >= 0 时,函数应返回 a + b,所以 h(a, b) 应为 add(a, b),h = add。
当 b < 0 时,同理应有 h = sub
from operator import add, sub, mul, neg
def a_add_abs_b(a, b):
if b >= 0:
h = add
else:
h = sub
return h(a, b)
当然,如果你不读题,也可以使用 lambda 解决这个问题。
def a_add_abs_b(a, b):
if b >= 0:
h = lambda a, b: a + b
else:
h = lambda a, b: a - b
return h(a, b)