362 recursive function

Read catalog

wedge

Before talking about the content of today, let's tell a story about what is it? There was once a mountain, the mountain there was a temple, the temple has an old monk telling stories, talking about what is it? There was once a mountain, the mountain there was a temple, the temple has an old monk telling stories, talking about what is it? There was once a mountain, the mountain there was a temple, the temple has an old monk telling stories, talking about what is it? There was once a mountain, the mountain there was a temple, the temple has an old monk telling stories, talking about what you do not ordered a halt to this story ...... I can speak day! We say that life examples can also be written as a program, just this story, let you write, how you write it?

while True:
    story = "
    从前有个山,山里有座庙,庙里老和尚讲故事,
    讲的什么呢?   
    "
    print(story)

You definitely have to be so written, but now we have learned function, and what should go into the function call is executed. So you would certainly say that, so I wrote:

Copy the code

def story():
    s = """
    从前有个山,山里有座庙,庙里老和尚讲故事,
    讲的什么呢?
    """
    print(s)
    
while True:
    story()

Copy the code

However, we take a look at how I write!

Copy the code

def story():
    s = """
    从前有个山,山里有座庙,庙里老和尚讲故事,
    讲的什么呢?
    """
    print(s)
    story()
    
story()

Copy the code

Regardless of the final first error function, in addition to the error, we can see it, this piece of code and the implementation of the above effect of the code is the same.

Recursion acquaintance

Recursive definitions - * in a function and then call this function itself *

Now that we probably know the story just talking about what the function does, is in a function and then call this function itself , this magic way to use a function is called recursively .

We just had to write a simple recursive function.

The maximum depth of recursion --997

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 997" mean? Here we can do an experiment:

img

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 997. 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:

img

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!

Talk about recursion

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 Jinxin.

Then you ask Jin Xin, Jin Xin tell you that he 40 a. . .

This time you is not know? alex much?

1 Jinxin 40
2 Wu sir 42
3 there 44
4 alex 46

Why can you know?

First of all, you are not asking alex age, the results found egon, Wu sir, Jin Xin, ask your children one by one 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 under such circumstances, we should be a function of how to write it?

Copy the code

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

print(age(4))

Copy the code

Recursive function and three-level menu

img

Copy the code

menu = {
    '北京': {
        '海淀': {
            '五道口': {
                'soho': {},
                '网易': {},
                'google': {}
            },
            '中关村': {
                '爱奇艺': {},
                '汽车之家': {},
                'youku': {},
            },
            '上地': {
                '百度': {},
            },
        },
        '昌平': {
            '沙河': {
                '老男孩': {},
                '北航': {},
            },
            '天通苑': {},
            '回龙观': {},
        },
        '朝阳': {},
        '东城': {},
    },
    '上海': {
        '闵行': {
            "人民广场": {
                '炸鸡店': {}
            }
        },
        '闸北': {
            '火车战': {
                '携程': {}
            }
        },
        '浦东': {},
    },
    '山东': {},
}

Copy the code

img

Copy the 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 the code

Remember prior written three menus work it? Now we use recursion to write about -

img

Copy the 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 the code

Guess you like

Origin www.cnblogs.com/jianjie/p/12470753.html