Python中的重复函数

6

我在Python的高阶函数方面遇到了困难。我需要编写一个名为repeat的函数,它将函数f在给定参数x上重复n次。

例如,repeat(f, 3, x)等同于f(f(f(x)))

这是我的代码:

def repeat(f,n,x):
    if n==0:
        return f(x)
    else:
        return repeat(f,n-1,x)

当我尝试断言以下代码时:

plus = lambda x,y: repeat(lambda z:z+1,x,y)
assert plus(2,2) == 4

我遇到了一个 AssertionError 错误。我看过关于 如何重复执行一个函数n次的问题,但是我需要按照这种方式完成它,而我无法做到...


f(x) 函数是否返回任何值?除非另有说明,否则它将返回 None - Savir
你想要得到 f(x) 的最后一次应用的结果吗? - thefourtheye
2
repeat 应该返回类似于 return f(repeat(f,n-1,x)) 这样的东西吗? - tgmath
作为一个更简单的例子,尝试 plus(0,2),它应该是2,但你的代码给出了3。它不会递归,所以调试应该很容易。 - Kevin
1
不要只是使用 assert,你可以尝试查看 plus 的实际返回值。使用不同的输入进行尝试,问题就会很容易被发现。 - interjay
由于问题不够清晰或需要大量澄清,因此进行关闭投票。 - thefourtheye
2个回答

5

你有两个问题:

  1. 你递归的次数不正确(如果 n == 1,函数应该只调用一次);并且
  2. 你没有在递归调用的返回值上调用 f,所以函数只被应用了一次。

尝试:

def repeat(f, n, x):
    if n == 1: # note 1, not 0
        return f(x)
    else:
        return f(repeat(f, n-1, x)) # call f with returned value

或者,另一种选择是:
def repeat(f, n, x):
    if n == 0:
        return x # note x, not f(x)
    else:
        return f(repeat(f, n-1, x)) # call f with returned value

(感谢@Kevin提供的后者,支持n == 0。)

示例:

>>> repeat(lambda z: z + 1, 2, 2)
4
>>> assert repeat(lambda z: z * 2, 4, 3) == 3 * 2 * 2 * 2 * 2
>>> 

5
最好使用 if n == 0: return x 而不是 if n == 1: return f(x),这样 plus(0,2) 仍然能够正常工作。 - Kevin

2

你在这里犯了一个非常简单的错误,在else代码块中,你只是将x传递下去而没有对它做任何处理。同时,当n == 0时,不要应用x。

def repeat(f,n,x):
    """
    >>> repeat(lambda x: x+1, 2, 0)
    2
    """
    return repeat(f, n-1, f(x)) if n > 0 else x

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接