日韩久久久精品,亚洲精品久久久久久久久久久,亚洲欧美一区二区三区国产精品 ,一区二区福利

讓你Python到很爽的加速遞歸函數的裝飾器

系統 2085 0

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

注記:鏈接“裝飾器”指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到很爽的加速遞歸函數的裝飾器,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對腳本之家網站的支持!


更多文章、技術交流、商務合作、聯系博主

微信掃碼或搜索:z360901061

微信掃一掃加我為好友

QQ號聯系: 360901061

您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。

【本文對您有幫助就好】

您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描上面二維碼支持博主2元、5元、10元、自定義金額等您想捐的金額吧,站長會非常 感謝您的哦!??!

發表我的評論
最新評論 總共0條評論
主站蜘蛛池模板: 威海市| 禄丰县| 松原市| 德阳市| 万盛区| 新巴尔虎右旗| 阳谷县| 河津市| 阿城市| 象州县| 全州县| 宁津县| 富阳市| 凉城县| 宜春市| 格尔木市| 长治县| 兰坪| 马龙县| 云梦县| 襄垣县| 武胜县| 赤峰市| 吉木萨尔县| 铁岭县| 达尔| 扬中市| 邻水| 白银市| 淮北市| 柳州市| 牟定县| 和顺县| 彰化市| 高淳县| 泰来县| 辽宁省| 宁晋县| 响水县| 黄浦区| 蛟河市|