python function Tutorial: Python recursive function parse binary search algorithm

This article introduces the next Python recursive function parse binary search algorithm, the paper sample code described in great detail, has a certain reference value of learning for all of us to learn or work, a friend in need can refer to
a initial recursive

Recursive function: in a function call to the function itself.

Maximum depth of recursion: 998

As you have just seen, a recursive function is blocked if the external force will not have been implemented. But as we have said before questions about the function call, every function call will have a space of its own name, if you have been to call it, would create a name space take up too much memory problems, so in order to stop this phenomenon python , forced the recursive layers of control in the 997 (as long as 997! you can not buy a disadvantage, not buy fooled ...).

What is to prove that this "theoretical 998" mean? Here we can do an experiment:

def foo(n):
  print(n)
  n += 1
  foo(n)
foo(1)

From this we can see that, before being given not able to see the maximum number is 998. Of course, the default value of 997 is a python program to optimize our memory of the set, of course, we also can modify it by some means:

import sys
print(sys.setrecursionlimit(100000))

We can modify the maximum depth of recursion in this way, we will just allow python recursion depth is set to 10w, as to the depth that can be achieved depends on the actual performance of the computer. But we still do not recommend to change this default recursion depth, because if the problem with recursive layer 997 does not solve either is not suitable for use recursion to solve either you write the code sucks ~ ~ ~

See here, you may find what recursion is also not a good thing, it is better while True easy to use it! However, this spread this word called on rivers and lakes: people understand the cycle, God understand recursion. So you can not underestimate recursive function, many people have been stopped outside the threshold of the Great God of so many years, it is not being able to comprehend the true meaning of recursion. And then we will study many algorithms and recursive relationship. Come on, I have only learned to despise the capital!

Second, the recursive example to explain
here, we have to give an example to illustrate recursion can do.

Example one:

Now you ask me, alex teacher how old? I said I did not tell you, but alex two years older than egon.

Alex you want to know how much you have to ask is not egon? egon say, I do not tell you, sir, but I contest two years older.

You asked Wu sir, no sir Wu told you, he said he was two years older than Bai.

Then you ask Bai, Bai told you, he 18 a.

This time you is not know? alex much? Here Insert Picture Description
Why can you know?

First of all, you are not asking alex age, the results found egon, Wu sir, Bai, one by one child asked you in the past, has been to get a definitive answer, then get it back along this line, before they get final alex of age. This process has been very close to the idea of ​​recursion. We come to me analyze specific, law between these people.

age(4) = age(3) + 2
age(3) = age(2) + 2
age(2) = age(1) + 2
age(1) = 40

That such a situation, a function of how we write it?

def age(n):
  if n == 1:
    return 40
  else:
    return age(n-1)+2
print(age(4))

If there is such a list allows you to find the location from the list of 66, how would you do?

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]
you say, so easy!

l.index(66)…

The reason why we can find by index method, because the python to help us achieve a lookup method. If, index method is not for you to use. . . You'll find that 66 it?

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]
i = 0
for num in l:
  if num == 66:
    print(i)
  i+=1

The above method to achieve a 66 to find where the location from a list.

But we find this number now is how ah? This list is not circulating, one by one to find it? If our list is particularly long, which take hundreds of thousands the number, then we find a number if bad luck is not to compare hundreds of thousands of times? This efficiency is too low, we have to think of a new way.

Binary search algorithm

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]
you look at this list, it is not a small to large sort of ordered list it?

If so, if I'm looking for a number greater than the number in the middle of the list, it is not directly to me on the line after the half of the list? Here Insert Picture Description
This is the binary search algorithm!

So we should implement the code on how to achieve it?

Simple dichotomy version

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)

An upgraded version of dichotomy

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))

Finally, we recommend a very wide python learning resource gathering, [click to enter] , here are my collection before learning experience, study notes, there is a chance of business experience, and calmed down to zero on the basis of information to project combat , we can at the bottom, leave a message, do not know to put forward, we will study together progress

Published 24 original articles · won praise 38 · views 20000 +

Guess you like

Origin blog.csdn.net/haoxun10/article/details/104761438