斐波那契数列的Python实现
斐波那契数列的Python实现:递归实现、非递归实现、斐波那契数列生成器;
\[\begin{equation}
F(n)=
\begin{cases}
n & n=0, 1\\
F(n-1) + F(n-2) & n > 1
\end{cases}
\end{equation}
\]
递归实现:
# python
def fib(n):
if n <= 1:
return n
else:
return fib(n-1) + fib(n-2)
非递归实现:
# python
def fib(n):
if n <= 1:
return n
else:
f1, f2, c = 0, 1, 0
for i range(n-1):
c = f1 + f2
f1, f2 = f2, c
return c
斐波那契数列生成器:
# python
def fib(n):
a, b, iter = 1, 0, -1
while iter < n:
yield b
# print(b)
a, b = b, a+b
iter += 1
for f in fib(10):
print(f)