Python3-只接受一个参数并使用递归返回列表的函数
以下是我目前的职能:Python3-只接受一个参数并使用递归返回列表的函数,python,python-3.x,recursion,Python,Python 3.x,Recursion,以下是我目前的职能: def fn_one(x): _list1 = [3, 1, 5, 3, 8, 5] if 5 < x < 14: return (fn_one(x-3) * fn_one(x-2)) + fn_one(x-1) else: if x < 6: return _list1[x] print(fn_one(7)) def fn_one(x): _列表1=[3,1,5,3,
def fn_one(x):
_list1 = [3, 1, 5, 3, 8, 5]
if 5 < x < 14:
return (fn_one(x-3) * fn_one(x-2)) + fn_one(x-1)
else:
if x < 6:
return _list1[x]
print(fn_one(7))
def fn_one(x):
_列表1=[3,1,5,3,8,5]
如果5
现在,我的函数只返回一个int,我要做的是返回一个列表,其中包含从0到该int的返回值。例如:假设我通过键入“print(fn_one(4)),调用该函数,然后我要返回一个列表,该列表为[fn_one(0),fn_one(1),fn_one(2),fn_one(3),fn_one(4)]通过仅使用递归。对于循环或类似的任何东西,都不能使用,并且函数必须只接受一个变量看起来您有一个函数
f
,使得f(k)
返回序列的k
第个项,并且您希望创建一个函数g
,使得g(k)
返回[f(0),…,f(k)]
基本上,在每种情况下,首先计算g(k-1)
,然后将最新的结果附加到其中
def fn_two(x):
_list1 = [3, 1, 5, 3, 8, 5]
if 5 < x < 14:
lst = fn_two(x-1)
lst.append((lst[x-3] * lst[x-2]) + lst[x-1])
return lst
else:
if x < 6:
# Return the first x values of _list1
return _list1[:x+1]
def fn_二(x):
_列表1=[3,1,5,3,8,5]
如果5
您已经有了列表1中的前六个数字,因此如果x<6
,您可以返回该列表的部分或全部,如下所示:
if x <= 5:
return _list1[:x + 2]
总而言之:
def fn_one(x):
_list1 = [3, 1, 5, 3, 8, 5]
if x <= 5:
return _list1[:x + 2]
else:
# returns the list formed by everything below element x
out_list = fn_one(x - 1)
# returns using values from the newly generated list
return out_list + [(out_list[-3] * out_list[-2]) + out_list[-1]]
def fn_one(x):
_列表1=[3,1,5,3,8,5]
如果x为什么if
在else
分支中?为什么上限为13?如果调用fn_one(14)
,会发生什么?我不理解函数的上半部分。这与你的例子有什么关系?另外,如果fn_one(x-3)*fn_one(x-2)
返回一个列表,那么应该怎么做?同样,如果你写fn_one(4)
应该返回[…,fn_one(4)]
,这是否意味着返回的列表应该无限嵌套引用自身?或者你是说,[[u list1[0],…,[u list1[4]]
相反?@MartijnPieters此时我不需要看13,所以我想我以后会处理它,至于“如果fn_one返回一个列表,fn_one(x-3)*fn_one(x-2)应该做什么?”这是我目前不知道如何处理的事情,这是我一直在寻找的!非常感谢您花时间和精力帮助我理解:)
def fn_one(x):
_list1 = [3, 1, 5, 3, 8, 5]
if x <= 5:
return _list1[:x + 2]
else:
# returns the list formed by everything below element x
out_list = fn_one(x - 1)
# returns using values from the newly generated list
return out_list + [(out_list[-3] * out_list[-2]) + out_list[-1]]