编写基于给定递归公式返回序列第n项的Python函数
用列表迭代实现递归序列的Python函数完善方案
需求说明
给定递归序列公式:
- 当n=2,3,…时,𝑓ₙ=1.5𝑓(𝑛−1)−0.5𝑓(𝑛−2)
- 初始项:𝑓₀=𝑠₀,𝑓₁=𝑠₁
需完善提供的Python函数,要求通过列表存储迭代过程中的每一项来实现,返回序列的第n项。
原初始代码
# function to produce n-th number of the following sequence: # f0=s0, f1=s1 (s0, s1 -- preset parameters) # f_n =1.5* f_{n-1} -0.5*f_{n-2} # Input: n, s0, s1 # Return: f_n def get_n_value(n, s0, s1): # handle special cases for the first three elements if n < 0: return 0 elif n == 0: return s0 elif n == 1: return s1 # the general case, n>1 else: # ADD YOUR CODE HERE # STORE THE FINAL RESULT IN fn VARIABLE return fn
完善后的代码
# function to produce n-th number of the following sequence: # f0=s0, f1=s1 (s0, s1 -- preset parameters) # f_n =1.5* f_{n-1} -0.5*f_{n-2} # Input: n, s0, s1 # Return: f_n def get_n_value(n, s0, s1): # handle special cases for the first three elements if n < 0: return 0 elif n == 0: return s0 elif n == 1: return s1 # the general case, n>1 else: # 初始化列表存储序列,先存入前两项 seq = [s0, s1] # 从第2项开始迭代计算到第n项 for i in range(2, n + 1): current = 1.5 * seq[i-1] - 0.5 * seq[i-2] seq.append(current) # 取第n项作为结果 fn = seq[n] return fn
实现说明
- 首先初始化列表
seq,把初始项s0和s1存入,作为序列的起点 - 通过
for循环从索引2(对应第2项)迭代到索引n,每次根据递归公式计算当前项,添加到列表末尾 - 最终直接从列表中取出第n个元素(索引为n)作为返回值
这种方式的优势:
- 可以完整保留整个序列,后续如果需要获取序列中其他项,无需重复计算
- 迭代实现比递归实现更高效,避免了递归调用可能导致的栈溢出问题,尤其当n值较大时表现更稳定
内容的提问来源于stack exchange,提问作者BornTie
相关产品推荐
相关产品推荐

