gpt4 book ai didi

python - 如何在python中编写递归函数

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:58:39 26 4
gpt4 key购买 nike

我已经在这个问题的解决方案上停留了很长一段时间,我写了一段代码可以按要求工作,但我似乎在编译结束时遇到了错误

You need to design an iterative and a recursive function called replicate_iter and replicate_recur respectively which will receive two arguments: times which is the number of times to repeat and data which is the number or string to be repeated.

The function should return an array containing repetitions of the data argument. For instance, replicate_recur(3, 5) or replicate_iter(3,5) should return [5,5,5]. If the times argument is negative or zero, return an empty array. If the argument is invalid, raise a ValueError.

我的代码如下:

def replicate_iter(times,data):

emptyArray = []
if not isinstance(data, int) and not isinstance(data, str):
raise ValueError
if times <= 0:
print emptyArray
if not isinstance(times,int):
raise ValueError
else:
while times > 0:
emptyArray.append(data)
times -= 1
return emptyArray

array = []

def replicate_recur(times,data):

if not isinstance(data,int) and not isinstance(data,str):
raise ValueError
if not isinstance(times,int):
raise ValueError
if times <= 0 and len(array) != 0:
return array
elif times <= 0 and len(array) <=0:
return []
else:
array.append(data)
replicate_recur(times - 1,data)

请多多指教

错误信息: enter image description here

最佳答案

首先,想一想:

def f(times,data):
return [] if times == 0 else f(times - 1,data) + [data]

print(f(3,5)) # [5,5,5]

现在,关于您的递归解决方案,(1) 为了访问 arrayreplicate_recur 需要在其开头声明,“global array ,"因为变量 array 是在函数范围之外声明的; (2) 将递归调用“replicate_recur(times - 1,data)”修改为“return replicate_recur(times - 1,data)”,以便当 times 大于零时实际返回值的函数。 (也就是说,据我所知,通常认为递归函数具有全局累加器是不受欢迎的形式。)

关于python - 如何在python中编写递归函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40829285/

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