python-函数装饰器的使用-25
来源:互联网 发布:业务流程编排 java 编辑:程序博客网 时间:2024/05/23 21:48
计算斐波那契数列。def fibonacci(n):
if n <= 1:
return 1
return fibonacci(n - 1) + fibonacci(n - 2)
print(fibonacci(3))
重复计算子问题,很浪费效率
解决这种重复计算子元素的问题我们可以使用缓存来解决。先在缓存中查找,缓存没有再尖酸,然后计算结果继续放在缓存中
升级代码:
def fibonacci(n,cache = None): if cache is None: cache = {} if n in cache: return cache[n] if n <= 1: return 1 cache[n] = fibonacci(n - 1,cache) + fibonacci(n - 2,cache) return cache[n]print(fibonacci(3))
再升级:使用装饰器添加缓存,相对来说不用改动源代码,透明
def memo(func): #闭包,在这个里面永远能访问到cache cache = {} def wrap(*args): if args not in cache: cache[args] = func(*args) return cache[args] return wrap@memodef fibonacci(n): if n <= 1: return 1 return fibonacci(n - 1) + fibonacci(n - 2)# fibonacci = memo(fibonacci) 相当于 @memoprint(fibonacci(50))
# -*- coding: utf-8 -*-# @Author: 96173# @Date: 2017-09-13 10:26:06# @Last Modified by: 96173# @Last Modified time: 2017-09-13 11:13:03# 利用函数装饰器解决重复计算子问题耗时过长问题 # 装饰器def memo(func): cache = {} # cache不会随着函数的消失而消失 def wrap(*args): if args not in cache: cache[args] = function(*args) return cache[args] return wrap # 斐波那契@memo # 等价于 fibonacci = memo(fibonacci)def fibonacci(n): if n <=1: return 1 return fibonacci(n-1) + fibonacci(n-2)# 斐波那契(升级)# def fibonacci(n,cache=None):# if cache is None:# cache = {}# if n in cache:# return cache[n]# if n <=1:# return 1# cache[n] = fibonacci(n-1,cache) + fibonacci(n-2,cache)# return cache[n]print(fibonacci(50))# 迈台阶多少种走法问题(回数法)@memodef climb(n,steps): count = 0; if n = 0: count = 1 elif n > 0: for step in steps: count += climb(n - step,steps) return countprint(climb(50,(1,2,3)))
0 0
- python-函数装饰器的使用-25
- python 使用函数装饰器的例子
- python函数装饰器的使用
- python的装饰器和find函数的使用
- Python 函数修饰符(装饰器)的使用
- python 装饰器的使用
- python装饰器的使用
- python 装饰器的使用
- python装饰器的使用
- python装饰器的使用
- python装饰器的4中类型:函数装饰函数、函数装饰类、类装饰函数、类装饰类
- Python: 使用装饰器“@”取得函数执行时间
- PYTHON 函数装饰器
- python 函数装饰器
- Python函数:装饰器
- Python 函数装饰器
- python函数装饰器
- python函数装饰器
- 170509 汇编-断点
- 蓝桥杯-K好数(java)
- G480BIOS刷新升级
- OpenGL学习笔记(七)
- bootstrap的两种模态框
- python-函数装饰器的使用-25
- D-4 Values whose Sum is 0
- adD
- 零售心理战-我喜欢的其中几句话
- zookeeper的若干应用场景
- 迁移学习技巧以及如何更好的finetune 模型
- apache的common中常用工具类
- 【数据结构基础】最大堆的基本操作
- eclipse安装yuicompressor插件