Recursive function, tertiary menu area

wedge

Before we talk about today's content, let's tell a story first. What is it about? Once upon a time there was a mountain, and there was a temple in the mountain. In the temple there was an old monk telling a story. What was he talking about? Once upon a time there was a mountain, and there was a temple in the mountain. In the temple there was an old monk telling a story. What was he talking about? Once upon a time there was a mountain, and there was a temple in the mountain. In the temple there was an old monk telling a story. What was he talking about? Once upon a time, there was a mountain, and there was a temple in the mountain. There was an old monk in the temple telling a story. What was he talking about... I can tell this story for a day if you don't stop it! We said that examples in life can also be written into programs. Just this story, let you write, how do you write it?

while True:
    story = "
    Once upon a time there was a mountain, and there was a temple in the mountain, where the old monks told stories,
    What are you talking about?   
    "
    print(story)

You must write like this, but now that we have learned about functions, everything must be called and executed in functions. So you're sure to say, I'll just write:

copy code
def story():
    s = """
    Once upon a time there was a mountain, and there was a temple in the mountain, where the old monks told stories,
    What are you talking about?
    """
    print(s)
    
while True:
    story()
copy code

But let's see how I wrote it!

copy code
def story():
    s = """
    Once upon a time there was a mountain, and there was a temple in the mountain, where the old monks told stories,
    What are you talking about?
    """
    print(s)
    story()
    
story()
copy code

Regardless of the last error report of the function, except for the error report, we can see that the execution effect of this piece of code is the same as that of the above code.

A first look at recursion

Definition of recursion - calling the function itself within a function

Now we have a general idea of ​​what the story function just mentioned is to call the function itself in a function . This magical way of using functions is called recursion .

Just now we have written a simplest recursive function.

Maximum depth of recursion - 997

As you have just seen, recursive functions continue to execute unless they are blocked by external forces. But we have already talked about the problem of function calls before. Each function call will generate a namespace of its own. If it keeps calling, it will cause the problem that the namespace occupies too much memory. Therefore, in order to prevent such phenomenon, python , the number of recursive layers is forced to be controlled at 997 (as long as 997! You can't buy a loss, you can't be fooled...).

What can be used to prove this "997 theory"? Here we can do an experiment:

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

From this we can see that the largest number that can be seen before an error is reported is 997. Of course, 997 is a default value set by python for the memory optimization of our program. Of course, we can also modify it by some means:

import sys
print(sys.setrecursionlimit(100000))

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 depth that can be achieved, it depends on the performance of the computer. However, we still do not recommend modifying this default recursion depth, because if you use 997 layers of recursion to solve the problem, either it is not suitable to use recursion to solve it or your code is too bad~~~

Seeing this, you may think that recursion is not such a good thing, it is not as easy to use while True! However, there is a saying circulating in the rivers and lakes called: People understand circulation, God understands recursion. So don't underestimate recursive functions. Many people have been blocked from the threshold of the Great God for so many years because they failed to understand the true meaning of recursion. And many of the algorithms we learn later will be related to recursion. Come on, only if you learn it will you be disgusted by capital!

Let's talk recursion again

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.

You want to know how old alex is, do you have to ask egon? I'm not telling you either, egon said, but I'm two years older than sir.

You ask Wu Sir again, Wu Sir does not tell you, he says he is two years older than Jin Xin.

Then you ask Jin Xin, Jin Xin tells you that he is 40. . .

Did you know it now? How old is alex?

1 Jin Xin   40
2 Wu sir   42
3 be   44
4 alex    46

Why do you know that?

First of all, did you ask alex's age, and you found egon, Wu sir, and Jinxin. You asked one by one until you got a definite answer, and then followed the line to find the final alex. age. This process is very close to the idea of ​​recursion. Let's analyze the rules between these people in detail.

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

In such a case, how should our function be written?

copy code
def age(n):
    if n == 1:
        return 40
    else:
        return age(n-1)+2

print(age(4))
copy code

 

Recursive function and tertiary menu

copy code
menu = {
    'Beijing': {
        'Haidian': {
            'Wudaokou': {
                'soho': {},
                'NetEase': {},
                'google': {}
            },
            'Zhongguancun': {
                'IQIYI': {},
                'Autohome': {},
                'youku': {},
            },
            'Uechi': {
                'Baidu': {},
            },
        },
        'Changping': {
            'Shahe': {
                'old boys': {},
                'Beihang': {},
            },
            'Tiantongyuan': {},
            'Huilongguan': {},
        },
        'Chaoyang': {},
        'Dongcheng': {},
    },
    'Shanghai': {
        'Minhang': {
            "People's Square": {
                'Fried Chicken': {}
            }
        },
        'Zhabei': {
            'train battle': {
                'Ctrip': {}
            }
        },
        'Pudong': {},
    },
    'Shandong': {},
}
copy code
copy code
1 def threeLM(dic):
 2     while True:
 3         for k in dic:print(k)
 4         key = input('input>>').strip()
 5         if key == 'b' or key == 'q':return key
 6         elif key in dic.keys() and dic[key]:
 7             ret = threeLM(dic[key])
 8             if ret == 'q': return 'q'

9
10 threeLM(menu)
copy code

Remember the three-level menu homework you wrote earlier? Now let's write it recursively

copy code
l = [menu]
while l:
    for key in l[-1]:print(key)
    k = input('input>>').strip()   # 北京
    if k in l[-1].keys() and l[-1][k]:l.append(l[-1][k])
    elif k == 'b':l.pop()
    elif k == 'q':break
copy code

 

Recursive function and binary search algorithm

http://www.cnblogs.com/Eva-J/articles/7197403.html

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325040456&siteId=291194637