法1:递归
def Fib1(n):
if n <= 1 :
return 1
else:
return Fib1(n-1)+ Fib1(n-2)
temp = []
def Fib1_list(n):
for i in range(n):
temp.append(Fib1(i))
return temp
a=Fib1_list(10)
print(a)
法2:循环
list=[]
def Fib2(n):
i = 0
a = 0
b = 1
while i < n:
a, b = b, a+b
list.append(a)
i+=1
return list
a=Fib2(10)
print(a)
法3:yield
def Fib3():
x,y=1,1
while True:
yield x
x,y=y,x+y
if __name__ == '__main__':
import itertools
print (list(itertools.islice(Fib3(),10)))
def Fib3(n):
a,b = 0,1
while n> 0:
yield b
a,b = b,a+b
n-=1
def Fib3_list(n):
# 此两个return语句皆可以返回斐波那契数列的列表
# return [f for i, f in enumerate(Fib3(n))]
return list(Fib3(n))
a=Fib3_list(10)
print(a)
法4:numpy
import numpy as np
M=np.matrix("1 1;1 0")
def Fib4(n):
M = np.matrix("1 1;1 0")
if n == 1:
return M
if n == 2:
return pow(M,2)
elif n % 2 == 1:
return Fib4((n-1)/2)**2*M
else:
return Fib4(n/2)**2
def Fib4_1(n):
M = np.matrix("1 1;1 0")
return pow(M,n)
def Fib4_2(n):
listA=[]
for i in range(n):
listA.append(np.array(Fib4_1(i)[0][0]))
return listA
print(Fib4(10))