我正在尝试编写一个根据以下公式生成数字的代码...
T[n] = 1 + T[n-1] * 2
numList = []
numLisst.append (1)
#Begins with a term 1.
def numSequence ():
while True:
for i in range (1,12):
#Temporally set numbers from 1 to 12
numList[i] == 1+(numList[i-1]*2)
break
print (numList)
numSequence()
首先,这会带来一个错误,列表索引超出索引
我希望看到这段代码生成斐波那契序列,例如,
1, 3, 7, 15, 31, 63, 127 , ....
我希望如果我使用这个递归程序,我能够找出数组中数字的特定顺序, 例如如果我想找出数组中的第三个数字,应该是 7 还是 15(这取决于我如何设置它)
最佳答案
假设您的基本情况是 T(1) = 1
def T(n):
if n == 1:
return 1
else:
return 1 + T(n-1)*2
一些例子
>>> [T(i) for i in range(1,10)]
[1, 3, 7, 15, 31, 63, 127, 255, 511]
>>> T(15)
32767
关于Python递归序列相关代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50154032/