让你Python到很爽的加速递归函数的装饰器

yipeiwu_com5年前Python基础

今天我们会讲到一个[装饰器]

注记:链接“装饰器”指Python3教程中的装饰器教程。可以在这里快速了解什么是装饰器。

@functools.lru_cache——进行函数执行结果备忘,显著提升递归函数执行时间。

示例:寻找宝藏。在一个嵌套元组tuple或列表list中寻找元素'Gold Coin'

import time
from functools import lru_cache
def find_treasure(box):
 for item in box:
  if isinstance(item, (tuple, list)):
   find_treasure(item)
  elif item == 'Gold Coin':
   print('Find the treasure!')
   return True
start = time.perf_counter()
find_treasure(('sth', 'sth', 'sth',
    ('Bad Coin', 'normal coin', 'fish', 'sth', 'any sth'),
    ('Bad Coin', 'normal coin', 'fish', 'sth', 'any sth'),
    'Gold Coin', ))
end = time.perf_counter()
run_time_without_cache = end - start
print('在没有Cache的情况下,运行花费了{} s。'.format(run_time_without_cache))
@lru_cache()
def find_treasure_quickly(box):
 for item in box:
  if isinstance(item, (tuple, list)):
   find_treasure(item)
  elif item == 'Gold Coin':
   print('Find the treasure!')
   return True
start = time.perf_counter()
find_treasure_quickly(('sth', 'sth', 'sth',
      ('Bad Coin', 'normal coin', 'fish', 'sth', 'any sth'),
      ('Bad Coin', 'normal coin', 'fish', 'sth', 'any sth'),
      'Gold Coin', ))
end = time.perf_counter()
run_time_with_cache = end - start
print('在有Cache的情况下,运行花费了{} s。'.format(run_time_with_cache))
print('有Cache比没Cache快{} s。'.format(float(run_time_without_cache-run_time_with_cache)))

最终输出

Find the treasure!
在没有Cache的情况下,运行花费了0.0002182829999810565 s。
Find the treasure!
在有Cache的情况下,运行花费了0.00011638000000857573 s。
有Cache比没Cache快0.00010190299997248076 s。

注记:运行这个示例时我的电脑配置如下

CPU:AMD Ryzen 5 2600
RAM:Kingston HyperX 8Gigabytes 2666

约使用7个月。

这个装饰器可以在函数运行时记录它的输入值与运行结果。当元组('Bad Coin', 'normal coin', 'fish', 'sth', 'any sth')出现第二次时,加了这个装饰器的函数find_the_treasure_quickly不会再次在递归时对这个元组进行查找,而是直接在“备忘录”中找到运行结果并返回!

总结

以上所述是小编给大家介绍的让你Python到很爽的加速递归函数的装饰器,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对【听图阁-专注于Python设计】网站的支持!

相关文章

python 下 CMake 安装配置 OPENCV 4.1.1的方法

python 下 CMake 安装配置 OPENCV 4.1.1的方法

CMake 安装配置 OPENCV 4.1.1 解决各种问题 方法一 python 可以直接pip install opencv-contrib-python==3.4.x.x 安装,老...

Python如何基于rsa模块实现非对称加密与解密

这篇文章主要介绍了Python如何基于rsa模块实现非对称加密与解密,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 1、简单介绍: R...

使用Python实现画一个中国地图

使用Python实现画一个中国地图

为什么是Python 先来聊聊为什么做数据分析一定要用Python或R语言。编程语言这么多种,Java, PHP都很成熟,但是为什么在最近热火的数据分析领域,很多人选择用Python语言...

Python兔子毒药问题实例分析

本文实例分析了Python兔子毒药问题。分享给大家供大家参考。具体分析如下: 问题大致是这样的:1000瓶无色无味的液体,其中一瓶为毒药,其它皆为清水,毒药只取一滴与清水混合为一瓶也可以...

Python进程间通信 multiProcessing Queue队列实现详解

一、进程间通信 IPC(Inter-Process Communication) IPC机制:实现进程之间通讯 管道:pipe 基于共享的内存空间 队列:pipe+锁的概念--->...