【问题标题】:Passing arguments down recursive functions将参数传递给递归函数
【发布时间】:2014-02-07 08:37:18
【问题描述】:

我想将第一次调用递归函数的参数传递给后面的调用:

例子:

def function(x):
    if base_case:
        return 4
    else:
        return function(x_from_the_first_call + x_from_this_call)

有没有比闭包更好的方法?

例如

def function(outer_x):
    def _inner(x)
        if base_case:
            return 4
        else:
            return function(outer_x + x)
    return _inner(outer_x)

【问题讨论】:

  • 你能让你的函数接受两个参数吗?然后只需分别传递两个值(初始调用的默认值)并将它们添加到函数中。
  • @BrenBarn 你认为这比关闭更干净吗?我这样做的问题是它会导致有一个额外的参数,这可能会使任何调用该函数的人不知道实现的人感到困惑,这让我觉得是一件坏事。
  • 我通常使用一个单独的命名参数,默认为None。并且“因为我们都是同意的成年人”在 python 中,大概任何更改该 arg 的调用者都有这样做的充分理由。

标签: python recursion closures scope


【解决方案1】:

如果你会在函数中以某种方式更改 x,那么我认为这应该可以工作:

def function(x, *args):
    if base_case:
        return 4
    else:
        new_x = x+1 # some change to x

        if args:
            # in args all previous x values

        # remove if in case if you need all previous values
        if not args:
            args.append(x)

        return function(new_x, *args)

【讨论】:

    猜你喜欢
    • 2014-06-27
    • 2020-05-15
    • 2013-01-27
    • 2021-04-18
    • 1970-01-01
    相关资源
    最近更新 更多