python 递归方式实现斐波那契数列

import time 

t1=time.time()
def factorial(n):

    if n==1 or n==2:
        return 1
    else:
        return factorial(n-1)+factorial(n-2)

f=factorial(30)
print(f)

delt1=time.time()-t1
print(delt1)

t2=time.time()
a=[1,1]

for i in range(2,30):
    d=a[i-1]+a[i-2]
    a.append(d)

print(i)
print(a[-1])

delt2=time.time()-t2
print(delt2)

print('the efficient is ',int(delt1/delt2))
832040
0.5144872665405273
29
832040
0.0003504753112792969
the efficient is  1467

可以看出递归的效率非常低,递归除了装13,并不实用…….

你可能感兴趣的:(算法与数据结构)