Python - 装饰器实现缓存
from functools import wraps
def cache(func):
cache = {}
@wraps(func)
def wrap(*args):
if args not in cache:
cache[args] = func(*args)
return cache[args]
return wrap
class Solution:
@cache
def fib(self, N):
if N < 2:
return N
else:
return self.fib(N - 2) + self.fib(N - 1)
或者
import functools
class Solution:
@functools.lru_cache(maxsize=None)
def fib(self, N):
"""
:type N: int
:rtype: int
"""
if N <= 1:
return N
else:
return self.fib(N - 1) + self.fib(N - 2)
Python - 装饰器实现缓存的更多相关文章
- python 装饰器 一篇就能讲清楚
装饰器一直是我们学习python难以理解并且纠结的问题,想要弄明白装饰器,必须理解一下函数式编程概念,并且对python中函数调用语法中的特性有所了解,使用装饰器非常简单,但是写装饰器却很复杂.为了讲 ...
- Python第二十六天 python装饰器
Python第二十六天 python装饰器 装饰器Python 2.4 开始提供了装饰器( decorator ),装饰器作为修改函数的一种便捷方式,为工程师编写程序提供了便利性和灵活性装饰器本质上就 ...
- 理解 Python 装饰器看这一篇就够了
讲 Python 装饰器前,我想先举个例子,虽有点污,但跟装饰器这个话题很贴切. 每个人都有的内裤主要功能是用来遮羞,但是到了冬天它没法为我们防风御寒,咋办?我们想到的一个办法就是把内裤改造一下,让它 ...
- python 装饰器、递归原理、模块导入方式
1.装饰器原理 def f1(arg): print '验证' arg() def func(): print ' #.将被调用函数封装到另外一个函数 func = f1(func) #.对原函数重新 ...
- Python 装饰器入门(上)
翻译前想说的话: 这是一篇介绍python装饰器的文章,对比之前看到的类似介绍装饰器的文章,个人认为无人可出其右,文章由浅到深,由函数介绍到装饰器的高级应用,每个介绍必有例子说明.文章太长,看完原文后 ...
- Python 装饰器使用指南
装饰器是可调用的对象,其参数是另一个函数(被装饰的函数). 1 装饰器基础知识 首先看一下这段代码 def deco(fn): print "I am %s!" % fn.__na ...
- 理解 python 装饰器
变量 name = 'world' x = 3 变量是代表某个值的名字 函数 def hello(name): return 'hello' + name hello('word) hello wor ...
- (转)python装饰器进阶一
Python装饰器进阶之一 先看例子 网上有很多装饰器的文章,上来说半天也没让人看明白装饰器到底是个什么,究竟有什么用,我们直接来看几个例子. Python递归求斐波那契数列 def fibonacc ...
- Python装饰器基础
一.Python装饰器引入 讲 Python 装饰器前,我想先举个例子,虽有点污,但跟装饰器这个话题很贴切. 每个人都有的内裤主要功能是用来遮羞,但是到了冬天它没法为我们防风御寒,咋办?我们想到的一个 ...
随机推荐
- Python Turtle模块的简单应用
时钟 import turtle as t import datetime as dt #画出背景 game = t.Screen() game.bgcolor("white") ...
- 2.2测试赛AC代码临时保存
//A #include<cstdio> #include<cstdlib> #include<algorithm> #include<cstring> ...
- python之路模块
time模块 print time.time() print time.mktime(time.localtime()) print time.gmtime() #可加时间戳参数 print time ...
- bugku 这么多数据包
看到之后有点懵逼 然后下载 下载之后发现是一个pacp后缀的流量数据包 然后用wireshark 然后只想到了 http过滤 然后发现不对 然后参考其他人的博客 经大佬提示, 一般 getshell ...
- Codeforces Round #600 (Div. 2) B. Silly Mistake
#include<iostream> #include<map> #include<set> #include<algorithm> using nam ...
- 用户登录(php)
<!DOCTYPE HTML><html><head><meta charset="utf-8"><script type=& ...
- 【原】librtmp源码详解
“悟已往之不谏,知来者之可追”.后悔做了这么久的直播,却不曾理解rtmp协议的实现原理,现在意识到了这个问题,特此补救.同时谨以此文纪念曾经的雷霄骅同学,感谢他对音视频领域做出的卓越贡献和引领. 1. ...
- ubuntu 安装谷歌
下载ubuntugoogle官网:http://www.ubuntuchrome.com/ 我的是ubuntuLTS稳定版: 上传Ubuntu: 执行解压操作: sudo dpkg -i goo ...
- css公共
@charset "utf-8"; /* CSS Document */ *{ padding:; margin:; } ul,li{ list-style: none; } a{ ...
- centOS7中启动MySQL数据库提示: Failed to start mysqld.service: Unit not foundc
现象: 在centOS7中启动MySQL数据库提示: Failed to start mysqld.service: Unit not found [明明已经安装了,为什么提示不存在呢?] 原因: 在 ...