Today, what we're going to talk about is the recursion of Python.
What is recursion? Look at the name, you may be able to guess a ballpark figure. With regard to recursion, we have a very classic application, which is our previous high school math problems in the multiplicative, like N * (n-1) * (n-2) * ... * 1. Here, if you want to calculate the final result, you might think of using a for loop, but we can do a little bit of optimization here, like this example:
# for loop def LSF (n): result = n for i in range (1,n): Result *= i return Result # recursive def LSF (n) if n = = 1: return 1 else : return n * LSF (n-1)
Let's take a look at the above two pieces of code, the first paragraph is implemented with a for loop, and the second is implemented recursively. Let's take a look at the difference between these two pieces of code, look at the for loop, simply define an interval, and then multiply each number in that interval and get the result we want. Focus on the recursive operation, first to determine whether N is 1, if it is 1, directly get the result, because n=1, we use the next code, the total result is 0, the result is not accurate, and then we exclude 1 of the situation, calculate the next value, the direct operation N * (n-1). Such code efficiency may not be high for a for loop, but it is much more readable.
Finally, let's talk about what binary search is, so-called binary search is an efficient way to find a certain data. For example, we have to find 81 this number in 0 to 100, we first put 0 to 100 in half, found that 81 between 50 and 100 we have another half points, found 81 between 75 and 100, so that, after several times in half, we find our number 81, This efficiency is much higher than we are from one to 100, how to implement it in code, we'll talk about it tomorrow.
OK, today's content is here!
(If the article image is infringing, please contact the author to delete)
Recursion for Python