重复函数python

重复函数python,python,Python,我被python中的高阶函数难住了。我需要编写一个repeat函数repeat,在给定参数x上应用函数fn次 例如,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

我被python中的高阶函数难住了。我需要编写一个repeat函数
repeat
,在给定参数
x
上应用函数
f
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==1
    ,则该函数应调用一次);及
  • 您没有对递归调用返回的值调用
    f
    ,因此该函数只应用一次
  • 尝试:

    或者,或者:

    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
    >>> 
    

    这里有一个非常简单的错误,在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
    

    f(x)
    函数是否返回任何内容?除非另有说明,否则它将返回
    None
    ,并且您希望得到上次应用
    f(x)
    ?不应
    重复
    返回类似
    的内容返回f(repeat(f,n-1,x))
    ?作为一个简单的示例,请尝试
    加上(0,2)
    ,它应该是2,但您的代码给出了3。它不会递归,因此应该很容易调试。您可以尝试查看
    plus
    的实际返回值,而不仅仅是
    assert
    ing。尝试使用不同的输入,很容易看出问题所在。如果n==0:return x
    ,则最好执行
    ,而不是
    如果n==1:return f(x)
    。这样,
    plus(0,2)
    仍然有效。
    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