Backend Development
Python Tutorial
How to implement pruning functions using high-order functions in python
How to implement pruning functions using high-order functions in python
This article mainly introduces in detail the relevant information on Python's use of higher-order functions to implement pruning functions. It has certain reference value. Interested friends can refer to it. I hope it can help everyone.
Case:
Sometimes, we want to add certain functions to multiple functions, such as timing statistics, logging, caching operation results, etc.
Requirements:
There is no need to add exactly the same code in each function
How to solve it?
Extract the same code and define it as a decorator
Find the Fibonacci sequence (golden section sequence), starting from the third item of the sequence, each item is Is equal to the sum of the first two terms
Find a staircase with a total of 10 steps. From the bottom to the top, you can only take 1 to 3 steps at a time, and you cannot go back. How many correct ways are there?
:
every time is 1 ~ 3 steps, the rest is 7-9 steps
If you take 1 step, you need to find the steps for the next 9 steps
If you take 2 steps, you need to find the steps for the next 8 steps
steps, you need to find the steps for the next 7 steps
These 3 ways of walking are realized through recursion. The recursion is like a tree, and each recursion generates child node functions
and above When the two problems are solved through recursion, a problem will arise, a repeated solution problem, and the repeated solution process will be eliminated. This is called a pruning function in the C++ language
#!/usr/bin/python3
def jian_zhi(func):
# 中间字典,判断已经是否求解过
median = {}
def wrap(*args):
# 假如不在中间字典中,说明没有求解过,添加到字典中去,在的话,直接返回
if args not in median:
median[args] = func(*args)
return median[args]
return wrap
@jian_zhi
def fibonacci(n):
if n <= 1:
return 1
return fibonacci(n-1) + fibonacci(n-2)
@jian_zhi
def climb(n, steps):
count = 0
# 当最后台阶为0的时候,说明最后只是走了一次
if n == 0:
count = 1
# 当最后台阶不为0的时候,说明还需要走至少一次
elif n > 0:
# 对三种情况进行分别处理momo
for step in steps:
count += climb(n-step, steps)
# 返回每次递归的计数
return count
if __name__ == '__main__':
print(climb(10, (1, 2, 3)))
print(fibonacci(20))The so-called pruning function is just to ensure the uniqueness of each recursion function. It uses an intermediate dictionary to save the executed functions and parameters, and eliminates repeated function calls by judging the parameters.
The above is the detailed content of How to implement pruning functions using high-order functions in python. For more information, please follow other related articles on the PHP Chinese website!
Hot AI Tools
Undress AI Tool
Undress images for free
Undresser.AI Undress
AI-powered app for creating realistic nude photos
AI Clothes Remover
Online AI tool for removing clothes from photos.
Clothoff.io
AI clothes remover
Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!
Hot Article
Hot Tools
Notepad++7.3.1
Easy-to-use and free code editor
SublimeText3 Chinese version
Chinese version, very easy to use
Zend Studio 13.0.1
Powerful PHP integrated development environment
Dreamweaver CS6
Visual web development tools
SublimeText3 Mac version
God-level code editing software (SublimeText3)
What are class methods in Python
Aug 21, 2025 am 04:12 AM
ClassmethodsinPythonareboundtotheclassandnottoinstances,allowingthemtobecalledwithoutcreatinganobject.1.Theyaredefinedusingthe@classmethoddecoratorandtakeclsasthefirstparameter,referringtotheclassitself.2.Theycanaccessclassvariablesandarecommonlyused
python asyncio queue example
Aug 21, 2025 am 02:13 AM
asyncio.Queue is a queue tool for secure communication between asynchronous tasks. 1. The producer adds data through awaitqueue.put(item), and the consumer uses awaitqueue.get() to obtain data; 2. For each item you process, you need to call queue.task_done() to wait for queue.join() to complete all tasks; 3. Use None as the end signal to notify the consumer to stop; 4. When multiple consumers, multiple end signals need to be sent or all tasks have been processed before canceling the task; 5. The queue supports setting maxsize limit capacity, put and get operations automatically suspend and do not block the event loop, and the program finally passes Canc
How to run a Python script and see the output in a separate panel in Sublime Text?
Aug 17, 2025 am 06:06 AM
ToseePythonoutputinaseparatepanelinSublimeText,usethebuilt-inbuildsystembysavingyourfilewitha.pyextensionandpressingCtrl B(orCmd B).2.EnsurethecorrectbuildsystemisselectedbygoingtoTools→BuildSystem→Pythonandconfirming"Python"ischecked.3.Ifn
How to use regular expressions with the re module in Python?
Aug 22, 2025 am 07:07 AM
Regular expressions are implemented in Python through the re module for searching, matching and manipulating strings. 1. Use re.search() to find the first match in the entire string, re.match() only matches at the beginning of the string; 2. Use brackets() to capture the matching subgroups, which can be named to improve readability; 3. re.findall() returns all non-overlapping matches, and re.finditer() returns the iterator of the matching object; 4. re.sub() replaces the matching text and supports dynamic function replacement; 5. Common patterns include \d, \w, \s, etc., you can use re.IGNORECASE, re.MULTILINE, re.DOTALL, re
How to build and run Python in Sublime Text?
Aug 22, 2025 pm 03:37 PM
EnsurePythonisinstalledbyrunningpython--versionorpython3--versionintheterminal;ifnotinstalled,downloadfrompython.organdaddtoPATH.2.InSublimeText,gotoTools>BuildSystem>NewBuildSystem,replacecontentwith{"cmd":["python","-
How to use variables and data types in Python
Aug 20, 2025 am 02:07 AM
VariablesinPythonarecreatedbyassigningavalueusingthe=operator,anddatatypessuchasint,float,str,bool,andNoneTypedefinethekindofdatabeingstored,withPythonbeingdynamicallytypedsotypecheckingoccursatruntimeusingtype(),andwhilevariablescanbereassignedtodif
How to pass command-line arguments to a script in Python
Aug 20, 2025 pm 01:50 PM
Usesys.argvforsimpleargumentaccess,whereargumentsaremanuallyhandledandnoautomaticvalidationorhelpisprovided.2.Useargparseforrobustinterfaces,asitsupportsautomatichelp,typechecking,optionalarguments,anddefaultvalues.3.argparseisrecommendedforcomplexsc
How to debug a remote Python application in VSCode
Aug 30, 2025 am 06:17 AM
To debug a remote Python application, you need to use debugpy and configure port forwarding and path mapping: First, install debugpy on the remote machine and modify the code to listen to port 5678, forward the remote port to the local area through the SSH tunnel, then configure "AttachtoRemotePython" in VSCode's launch.json and correctly set the localRoot and remoteRoot path mappings. Finally, start the application and connect to the debugger to realize remote breakpoint debugging, variable checking and code stepping. The entire process depends on debugpy, secure port forwarding and precise path matching.


