gpt4 book ai didi

python - 重复函数python

转载 作者:太空狗 更新时间:2023-10-29 23:59:00 24 4
gpt4 key购买 nike

我被 python 中的高阶函数困住了。我需要编写一个重复函数 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。我读到了 How to repeat a function n times但我需要以这种方式完成,但我无法弄清楚...

最佳答案

你有两个问题:

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

关于python - 重复函数python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24264420/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com