import time
# 斐波那契传统递归方法,属于二路递归,重复计算数值,计算效率非常低,随着n的增大,需要递归的次数将呈指数级增长
def bad_feibo(n):
if n <= 1:
return 1
return bad_feibo(n-1)+bad_feibo(n-2)
# 在返回结果时,将前一个值顺带回来,这样随着n的增大,需要递归的次数呈线性增长,该优化将能大大提升递归效率
def good_feibo(n):
def imp_feibo(n):
if n <= 1:
return (0, 1)
a, b = imp_feibo(n-1)
return (b, a+b)
return sum(imp_feibo(n))
start = time.time()
a = bad_feibo(36)
print('bad_feibo: %s time: %s' % (a, time.time()-start))
start = time.time()
b = good_feibo(36)
print('good_feibo: %s time: %s' % (b, time.time()-start))
# bad_feibo: 24157817 time: 4.94177293777
# good_feibo: 24157817 time: 1.90734863281e-05
# 计算某个数的指数结果,随着指数的增加,需要递归的次数呈线性增长,属于线性递归
def bad_exp(x, r):
def imp_exp(r):
if r == 0:
return 1
return x*imp_exp(r-1)
return imp_exp(r)
# 利用乘法的特性,随着指数的增加,需要递归的次数呈现对数增长,属于线性递归,在该例子中,优化的结果为计算时间少了一个数量级
def good_exp(x, r):
def imp_exp(r):
if r == 0:
return 1
if r == 1:
return x
mid = r // 2
rst = imp_exp(mid)
rst = rst*rst
if r % 2 == 1:
rst *= x
return rst
return imp_exp(r)
start = time.time()
a = bad_exp(2, 100)
print('bad_exp: %s time: %s' % (a, time.time()-start))
start = time.time()
b = good_exp(2, 100)
print('good_exp: %s time: %s' % (b, time.time()-start))
# bad_exp: 1267650600228229401496703205376 time: 5.50746917725e-05
# good_exp: 1267650600228229401496703205376 time: 5.96046447754e-06