Skip to content

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 模块导入的 addsubmulneg 函数。

  • 这些运算符的文档:operator

  • 注意 h 是一个函数,所以填空的地方也要填一个函数。

Solutions