求斐波那契数列的第n项:
def fib1(n):
if n == 1:
return 0
elif n ==2:
return 1
else:
return fib1(n-1) + fib1(n-2)
fib1(3)
# 1
求斐波那契数列的前n项:
def fib2(n):
if n == 1:
return [0]
elif n == 2:
return [0,1]
else:
list1 = fib2(n-1)
list1.append(list1[-1] + list1[-2])
return list1
fib2(5)
# [0, 1, 1, 2, 3]
通过迭代器实现求斐波那契数列:
def fib3():
a = 0
b = 1
while 1:
yield a
a,b = b,a + b
number_fib = fib3() #生成器返回一个迭代器
[next(number_fib) for i in range(10)]
#[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]