这是一个在线的有趣问题.
为了编写递归函数,我们总是使用def或赋值语句为其命名,以便我们可以在其自身体内引用该函数.在这个问题中,您的工作是递归地定义它,而不给它命名!
Write an expression to complete the function make_anonymous_factorial(),which 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.
e.g.
>>> make_anonymous_factorial( )(5)
120
以下是我的解决方案:
from operator import sub, mul
def make_anonymous_factorial():
from functools import reduce
return lambda n:reduce(mul, range(1, n + 1))
然而,正如问题The sub and mul functions from the operator module are the only built-in functions required to solve this problem所描述的那样,由于我使用了reduce(),我认为这不是一个合适的答案.
有更好的解决方案吗?
(问题来自cs61a summer 2020 HW03、Q6和here is the link.这是页面底部的最后一个问题.)