我正在使用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]
答案 0 :(得分:2)
您要实现的方程是closed form斐波那契数列。
闭合形式表示求值是恒定时间操作。
g = (1 + 5**.5) / 2 # Golden ratio.
def fib(N):
return int((g**N - (1-g)**N) / 5**.5)
与
对比def fib_iterative(N):
a, b, i = 0, 1, 2
yield from (a, b)
while i < N:
a, b = b, a + b
yield b
i += 1
我们有
>>> [fib(n) for n in range(10)]
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
>>> list(fib_iterative(10))
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
答案 1 :(得分:1)