日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

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

發布時間:2024/9/30 python 24 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python 递归函数_让你Python到很爽的加速递归函数的装饰器 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

Python技巧——好用的一個裝飾器

今天我們會講到一個裝飾器。

注記:鏈接“裝飾器”指向廖雪峰老師的Python3教程中的裝飾器教程。可以在這里快速了解什么是裝飾器。

`@functools.lru_cache`——進行函數執行結果備忘,顯著提升遞歸函數執行時間。

示例:尋找寶藏。在一個嵌套元組`tuple`或列表`list`中尋找元素`'Gold Coin'`

import time from functools import lru_cachedef find_treasure(box):for item in box:if isinstance(item, (tuple, list)):find_treasure(item)elif item == 'Gold Coin':print('Find the treasure!')return Truestart = 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 - startprint('在沒有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 Truestart = 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 - startprint('在有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 2600RAM:Kingston HyperX 8Gigabytes 2666
約使用7個月。

這個裝飾器可以在函數運行時記錄它的輸入值與運行結果。當元組('Bad Coin', 'normal coin', 'fish', 'sth', 'any sth')出現第二次時,加了這個裝飾器的函數find_the_treasure_quickly不會再次在遞歸時對這個元組進行查找,而是直接在“備忘錄”中找到運行結果并返回!

總結

以上是生活随笔為你收集整理的python 递归函数_让你Python到很爽的加速递归函数的装饰器的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。