Recursive function: Call the function itself within a function.
Maximum depth of recursion: 998
As you just saw, the recursive function will continue to execute if it is not blocked by external forces. But we have already talked about the problem of function calls before. Each function call will generate a name space of its own. If it is called continuously, it will cause the name space to occupy too much memory, so Python is trying to prevent this kind of phenomenon. , forcibly controlling the number of recursion levels to 997 (as long as 997! You can’t suffer losses or be fooled...).
What can be used to prove this "998 theory"? Here we can do an experiment:
def foo(n):
print(n)
n += 1
foo(n)
foo(1)
Copy after login
From this we can see that the maximum number that can be seen before an error is reported is 998. Of course, 997 is a number set by python for the memory optimization of our program. Default value, of course we can also modify it through some means:
import sys
print(sys.setrecursionlimit(100000))
Copy after login
We can modify the maximum depth of recursion in this way. We just set the recursion depth allowed by python to 10w. As for the actual recursion depth, it can be reached The depth depends on the performance of the computer. However, we still do not recommend changing this default recursion depth, because if the problem cannot be solved with 997 levels of recursion, it is either not suitable to use recursion to solve it, or your code is too poorly written~~~
Look At this point, you may feel that recursion is not such a good thing, and it is not as useful as while True! However, there is a saying circulating in the world: humans understand cycles, gods understand recursion. So don’t underestimate recursive functions. Many people have been blocked from the threshold of great masters for so many years because they failed to understand the true meaning of recursion. And many of the algorithms we learn in the future will be related to recursion. Come on, only if you learn it will you have the capital to dislike it!
2. Recursive example explanation
Here we will give another example to illustrate what recursion can do.
Example 1:
Now you ask me, how old is Mr. Alex? I said I won't tell you, but Alex is two years older than egon.
If you want to know how old Alex is, do you still have to ask Egon? egon said, I won’t tell you either, but I am two years older than Sir Wu.
You asked Sir Wu again, but Sir Wu didn’t tell you either. He said he was two years older than Taibai.
Then you ask Taibai, Taibai will tell you that he is 18.
l = [2,3,5,10,15,16,18,22,26,30,32,35,41,42,43,55,56,66,67,69,72,76,82,83,88]
Copy after login
Copy after login
你观察这个列表,这是不是一个从小到大排序的有序列表呀?
如果这样,假如我要找的数比列表中间的数还大,是不是我直接在列表的后半边找就行了?
这就是二分查找算法!
那么落实到代码上我们应该怎么实现呢?
简单版二分法
l = [2,3,5,10,15,16,18,22,26,30,32,35,41,42,43,55,56,66,67,69,72,76,82,83,88]def func(l,aim):
mid = (len(l)-1)//2
if l: if aim > l[mid]:
func(l[mid+1:],aim) elif aim < l[mid]:
func(l[:mid],aim) elif aim == l[mid]:
print("bingo",mid) else:
print('找不到')
func(l,66)
func(l,6)
Copy after login
升级版二分法
l1 = [1, 2, 4, 5, 7, 9]
def two_search(l,aim,start=0,end=None):
end = len(l)-1 if end is None else end
mid_index = (end - start) // 2 + start
if end >= start:
if aim > l[mid_index]:
return two_search(l,aim,start=mid_index+1,end=end
elif aim < l[mid_index]:
return two_search(l,aim,start=start,end=mid_index-1)
elif aim == l[mid_index]:
return mid_index
else:
return '没有此值'
else:
return '没有此值'
print(two_search(l1,9))
Copy after login
The above is the detailed content of Python recursive function, introduction to binary search algorithm. For more information, please follow other related articles on the PHP Chinese website!
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.
PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.
PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.
Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.
To run Python code in Sublime Text, you need to install the Python plug-in first, then create a .py file and write the code, and finally press Ctrl B to run the code, and the output will be displayed in the console.
Writing code in Visual Studio Code (VSCode) is simple and easy to use. Just install VSCode, create a project, select a language, create a file, write code, save and run it. The advantages of VSCode include cross-platform, free and open source, powerful features, rich extensions, and lightweight and fast.
VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.
Running Python code in Notepad requires the Python executable and NppExec plug-in to be installed. After installing Python and adding PATH to it, configure the command "python" and the parameter "{CURRENT_DIRECTORY}{FILE_NAME}" in the NppExec plug-in to run Python code in Notepad through the shortcut key "F6".