我使用Python用这个公式来创建一个斐波那契:
我有这个递归斐波那契功能:
def recursive_fibonacci(n):
if n <= 1:
return int((((1 / (5 ** 0.5)) * (1 + (5 ** 0.5))) ** n) - (((1 / (5 ** 0.5)) * (1 - (5 ** 0.5))) ** n))
else:
return(recursive_fibonacci(n - 1) + recursive_fibonacci(n - 2))
要显示它我使用这样的:
nterms = 10
if nterms <= 0:
print("Please Enter a positive integer")
else:
print("Recursive Fibonacci Sequence: " ,
[recursive_fibonacci(i) for i in range(nterms)])
print("Iterative Fibonacci Sequence: " ,
[iterative_fib(i) for i in range(nterms)])
我将如何使用迭代函数与此斐波那契?
我已经使用这个尝试:
def iterative_fib(n):
equation = lambda n: int((((1 / (5 ** 0.5)) * (1 + (5 ** 0.5))) ** n) - (((1 / (5 ** 0.5)) * (1 - (5 ** 0.5))) ** n))
if n <= 1:
return equation(n)
else:
a, b = 1, 2
for i in range(n):
fn = equation((i-a)+(i-b))
return fn
然而,这迭代函数似乎不具备输出作为递归函数相同。
递归函数的输出:
Recursive Fibonacci Sequence: [0, 2, 2, 4, 6, 10, 16, 26, 42, 68]
迭代函数的输出:
Iterative Fibonacci Sequence: [0, 2, 2, 2, 3, 6, 13, 27, 58, 122]