我应该创建一个在Python中生成Tribonacci序列的函数。此功能必须 RECURSIVE 。基于此,到目前为止我有这个代码:
def TribRec(n) :
if (n == 0 or n == 1 or n == 2) :
return []
elif (n == 3) :
return [0,1][:n]
else :
sequence = TribRec(n-1)
sequence.append(sequence[len(sequence)-1] +
sequence[len(sequence)-2] + sequence[len(sequence)-3])
return sequence
def Trib(n) :
for i in range(1, n) :
print( TribRec(i) , " ", end = "")
# Driver code
n = 10
Trib(n)
当我运行此代码时,我得到以下输出:
[] [] [0, 1] [0, 1, 2] [0, 1, 2, 3] [0, 1, 2, 3, 6] [0, 1, 2, 3, 6, 11] [0, 1,2, 3, 6, 11, 20] [0, 1, 2, 3, 6, 11, 20, 37]
相反,我希望length = n的输出在这里以10的形式出现:
[0, 1, 2, 3, 6, 11, 20, 37, 68, 125]
如何修复当前代码?
答案 0 :(得分:1)
您的代码可以更简洁地编写如下。
def TribRec(n) :
if n in {0, 1, 2}:
return n
else :
return TribRec(n-1) + TribRec(n-2) + TribRec(n-3)
def Trib(n) :
for i in range(0, n) :
yield TribRec(i)
res = list(Trib(10))
# [0, 1, 2, 3, 6, 11, 20, 37, 68, 125]
<强>解释强>
TribRec
。n
,则返回{0, 1, 2}
。Trib(n)
,使用生成器删除样板代码(列表实例化,附加到列表)。答案 1 :(得分:0)
不是在每次递归调用中返回一个列表,而是返回第n个元素并在Trib
函数上聚合列表:
def TribRec(n) :
if n == 0:
return 0
elif n == 1:
return 1
elif n == 2:
return 2
else :
return TribRec(n-1) + TribRec(n-2) + TribRec(n-3)
def Trib(n) :
l = []
for i in range(0, n) :
l.append(TribRec(i))
return l
# Driver code
n = 10
Trib(n)
答案 2 :(得分:0)
这更简单:
def trib(n):
if n < 3:
return n
return trib(n-1) + trib(n-2) + trib(n-3)
def tri(n):
result = []
for i in range(0,n):
result.append(trib(n))
return result