Skip to content

Problem 7: Anonymous factorial (1pts)

Problem

The recursive factorial function can be written as a single expression by using a conditional expression.

>>> fact = lambda n: 1 if n == 1 else mul(n, fact(sub(n, 1)))
>>> fact(5)
120

The ternary operator <a> if <bool-exp> else <b> evaluates to <a> if <bool-exp> is truthy and evaluates to <b> if <bool-exp> is false-y.

However, this implementation relies on the fact (no pun intended) that fact has a name, to which we refer in the body of fact. To write a recursive function, we have always given it a name using a def or assignment statement so that we can refer to the function within its own body. In this question, your job is to define fact recursively without giving it a name!

Write an expression that computes n factorial using only call expressions, conditional expressions, and lambda expressions (no assignment or def statements). Note in particular that you are not allowed to use make_anonymous_factorial in your return expression. The sub and mul functions from the operator module are the only built-in functions required to solve this problem:

递归阶乘函数可以通过使用条件表达式写成一个单独的表达式。

>>> fact = lambda n: 1 if n == 1 else mul(n, fact(sub(n, 1)))
>>> fact(5)
120

三元运算符 <a> if <bool-exp> else <b><bool-exp> 为真值时求值为 <a>,在 <bool-exp> 为假值时求值为 <b>

然而,这个实现依赖于 fact 有一个名字这一事实(并非双关),我们在 fact 的函数体中引用了这个名字。为了编写一个递归函数,我们总是使用 def 或赋值语句给它一个名字,以便我们可以在函数体内部引用该函数。在这个问题中,你的任务是不给阶乘函数命名,而是以递归方式定义它!

编写一个仅使用调用表达式、条件表达式和 lambda 表达式(没有赋值或 def 语句)来计算 n 阶乘的表达式。特别注意,你不能在你的返回表达式中使用 make_anonymous_factorial operator 模块中的 submul 函数是解决此问题所需的唯一内置函数:

from operator import sub, mul


def make_anonymous_factorial():
    """Return the value of an expression that computes factorial.

    >>> make_anonymous_factorial()(5)
    120
    >>> from construct_check import check
    >>> # ban any assignments or recursion
    >>> check(HW_SOURCE_FILE, 'make_anonymous_factorial', ['Assign', 'AugAssign', 'FunctionDef', 'Recursion'])
    True
    """
    return "YOUR_EXPRESSION_HERE"

Hints

  • 建议先做下一道题。思路很像。