【问题标题】:Does Python have a `nest` function like Mathematica?Python 是否有像 Mathematica 这样的“嵌套”函数?
【发布时间】:2021-03-28 09:40:08
【问题描述】:

Mathematica 有一个方便的 Nest 函数,用于重复评估 f(f(f(f(...f(n)))))。不是你每天都需要的东西,但偶尔有用。这是一个简单的实现:

def nest(f, expr, n):
    assert n >= 0
    if n == 0:
        return expr
    else:
        return f(nest(f, expr, n - 1))
>>> nest(lambda x: (1 + x) ** 2, 1, 3)
676

有没有 Pythonic 的方式来做到这一点?

【问题讨论】:

  • 你有什么问题?
  • 一个更方便的方法可能是考虑使用reduce 模式。 map/reduce 模式可以很容易地分发,您的问题可以表示为 reduce 表达式(在更一般的方式上略有不同)。
  • 这能回答你的问题吗? How to repeat a function n times;特别是this answer
  • 另外this answer 到另一个问题建议def compose(f, x, n): return functools.reduce( lambda x, _: f(x), range(n), x)

标签: python function recursion functional-programming wolfram-mathematica


【解决方案1】:

也许如果你喜欢这些东西,你可以关注functools.reduce

from functools import reduce

def nest(f, expr, n):
    return reduce(lambda x, _: f(x), range(n), expr)
>>> nest(lambda x: (1 + x) ** 2, 1, 3)
676

【讨论】:

    【解决方案2】:

    说到 Pythonic,这是一个基于意见的概念,我想说一个简单的迭代实现 (Readability being a core Python principle) 比基于 reduce 或递归的方法更具可读性:

    def nest(f, expr, n):
        for _ in range(n):
            expr = f(expr)
        return expr
    

    当然,我不必像在其他情况下那样盯着这里发生的事情。但是,如果您追求简洁,则可以使用条件表达式:

    def nest(f, expr, n):
        return f(nest(f, expr, n - 1)) if n else expr
    

    【讨论】:

    • 我实际上完全同意你的看法。我提供了一个reduce 的答案,作为一个半开玩笑的评论。事实上,我喜欢 Guido Himself 的这个(过时的,但相关的)post。 (另外,在我的辩护中,十多年来为 PB 级问题开发 map-reduce 算法给我留下了终生的伤痕——不过我承认这很有趣)。
    • 我没有批评的意思(你的优点之一来自我)。我喜欢那里创造性地使用reduce。如果 OP 喜欢那种功能性的巫术,那可能就在他们的小巷里 =)
    猜你喜欢
    • 1970-01-01
    • 2013-03-06
    • 1970-01-01
    • 2015-12-06
    • 1970-01-01
    • 1970-01-01
    • 2018-07-26
    • 2023-03-06
    • 2012-10-14
    相关资源
    最近更新 更多