之前用python简单写了一下斐波那契数列的递归实现(如下),发现运行速度很慢。
def fib_direct(n): assert n > 0, ‘invalid n‘ if n < 3: return n else: return fib_direct(n - 1) + fib_direct(n - 2)
然后大致分析了一下fib_direct(5)的递归调用过程,如下图:
住:这里的f(2)调用f(1)仅代表基本操作的次数。
可以看到多次重复调用,因此效率十分低。进一步,可以算出递归算法的时间复杂度
。T(n) = T(n-1) + T(n-2),用常系数线性齐次递推方程的解法,解出递推方程的特征根,特征根里最大的n次方就是它的时间复杂度O(1.618^n),指数级增长。
为了避免重复调用,可以适当地做缓存,python的装饰器可以完美的完成这一任务。
装饰器:基础
python中一切都是对象,这里需要强调函数是对象
。为了更好地理解函数也是对象,下面结合代码片段来说明这一点。
#! /usr/bin/env python def shout(word=‘yes‘): return word.capitalize() + ‘!‘ print shout() #outputs:Yes! ‘‘‘ As an object, you can assign the function to a variable like any other object. Notece we don‘t use parentheses: we are not calling the function, we are putting the function ‘shout‘ into the variable ‘scream‘. ‘‘‘ scream = shout print scream() #outputs:Yes! ‘‘‘ More than that, it meams you can remove the old name ‘shout‘, and the function will still be accessible from ‘scream‘. ‘‘‘ del shout try: print shout() except NameError, e: print e #outputs:name ‘shout‘ is not defined print scream() #outputs:Yes!
http://selfboot.cn/2014/08/10/python_decorator/
原文:http://www.cnblogs.com/stemon/p/5087062.html