Python allows you to cool accelerating recursive function decorator!

Python skills - easy to use a decorator

Today we will talk about a [decorator]

@ Functools.lru_cache - were the results of the memo function, significantly improved recursive function execution time.

Example: to find the treasure. Looking in the tuple or tuple list in a nested list element '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!
Under no circumstances Cache, run took 0.0002182829999810565 s.
Find the treasure!
In the case of Cache case, it took to run the 0.00011638000000857573 s.
There Cache faster than 0.00010190299997248076 s not Cache.
Notes: When you run this example, my computer configuration is as follows

CPU:AMD Ryzen 5 2600

RAM:Kingston HyperX 8Gigabytes 2666

About 7 months. Python learning exchange group: 1004391443, there are shared resources, technical solutions, as well as small series are finishing from the most basic Python data to project combat learning materials, hoping to help you better understand the python, python learning

This decoration can record its input value and operation results function is running. When the tuple ( 'Bad Coin', 'normal coin', 'fish', 'sth', 'any sth') when the second time, the addition of this function decorator find_the_treasure_quickly this element will not again recursive group to find, but to find operating results directly in the "memo" and returns!

Guess you like

Origin blog.csdn.net/weixin_34408624/article/details/90923042