重复函数python
我被python中的高阶函数难住了。我需要编写一个repeat函数重复函数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
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