gpt4 book ai didi

Python递归序列相关代码

转载 作者:行者123 更新时间:2023-11-30 22:15:53 29 4
gpt4 key购买 nike

我正在尝试编写一个根据以下公式生成数字的代码...

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/

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