这是一个在线的有趣问题.

为了编写递归函数,我们总是使用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.这是页面底部的最后一个问题.)

推荐答案

在阅读了Frank提到的关于函数自身作为参数的文章后,我try 了(Try it online!):

from operator import sub, mul

def make_anonymous_factorial():
    return (lambda f: lambda n: f(n, f))(
        lambda n, f: mul(n, f(sub(n, 1), f)) if n else 1
    )

print(make_anonymous_factorial()(5))

最里面的lambda n, f:是真正的阶乘计算机,它将自己作为第二个参数.这是由外部两个lambda组织的.lambda n:是我返回的,它称为n和它本身的实阶乘.

Python相关问答推荐

Pandas使用过滤器映射多列

使用Python C API重新启动Python解释器

Plotly:如何更改Heatmap中彩色条的勾选文本

Pandas 除以一列中出现的每个值

Pythind 11无法弄清楚如何访问tuple元素

Pandas 在最近的日期合并,考虑到破产

如何删除索引过go 的lexsort深度可能会影响性能?' &>

2D空间中的反旋算法

通过pandas向每个非空单元格添加子字符串

将tdqm与cx.Oracle查询集成

有没有一种方法可以从python的pussompy比较结果中提取文本?

我对我应该做什么以及我如何做感到困惑'

Django—cte给出:QuerySet对象没有属性with_cte''''

Django admin Csrf令牌未设置

从Windows Python脚本在WSL上运行Linux应用程序

如何使用Numpy. stracards重新编写滚动和?

将标签移动到matplotlib饼图中楔形块的开始处

如何将数据帧中的timedelta转换为datetime

如何求相邻对序列中元素 Select 的最小代价

在Python中控制列表中的数据步长