python--recursive function--Jingliyang

Source: Internet
Author: User

Wedge

Before we talk about today's content, let's start with a story, what does it say? There used to be a mountain, there was a temple in the mountain, there was an old monk in the temple telling the story, what was it about? There used to be a mountain, there was a temple in the mountain, there was an old monk in the temple telling the story, what was it about? There used to be a mountain, there was a temple in the mountain, there was an old monk in the temple telling the story, what was it about? There used to be a mountain, there was a temple in the mountain, there was an old monk in the temple to tell the story, what to say ... This story you don't shout stop I can speak one day! We say that the example of life can also be written in the program, just this story, let you write, how do you write?

While True:    story = "    there used to be a mountain, there was a temple in the mountain, the old monk in the temple told stories,    what was it about?"       "    print (story)

You must have written this, but now that we have learned the function, everything is put into the function to invoke and execute. So you're going to say, I just wrote:

def story ():    s = ""    there used to be a mountain, a temple in the mountains, the old monk in the temple telling stories,    what about? "" "    print (s) while    True: Story    ()

But let's see how I wrote it!

def story ():    s = ""    there used to be a mountain, a temple in the mountains, the old monk in the temple telling stories,    what about? ""    print (s) story () Stories    ()

Regardless of the function at the end of the error, in addition to the error, we can see that this piece of code and the above code execution effect is the same.

Back to Top

Primary knowledge recursion

Recursive definition-- call the function itself in a function

Now we probably know what the story function has just been doing, which is to call the function itself in a function , and this magic way of using the function is called recursion .

We've just written one of the simplest recursive functions.

Max depth of recursion--997

As you have just seen, recursive functions are carried out if they are not blocked by external forces. But as we've said before about function calls, each time a function call produces a namespace that belongs to it, and if it keeps calling, it causes the namespace to take up too much memory, so Python is forced to control the recursive layer by 997 in order to eliminate this kind of phenomenon. (only 997!) You can not buy the loss, can not buy fooled ...).

What does it take to prove the "997 theory"? Here we can do an experiment:

def foo (n):    print (n)    n + = 1    foo (n) foo (1)
test maximum recursion depth

From this we can see that the maximum number that can be seen before an error is 997. Of course, 997 is a default value that Python sets for the memory optimization of our program, and of course we can modify it by some means:

Import Sysprint (Sys.setrecursionlimit (100000))
Modify recursive maximum depth

We can modify the maximum depth of recursion in this way, just as we set the recursive depth allowed by Python to 10w, and the actual depth that can be reached depends on the performance of the computer. However, it is still not recommended to modify this default recursion depth, because if the 997-layer recursion is not solved the problem is either not suitable for the use of recursive resolution or you write code is too bad ~ ~ ~

See here, you may feel that recursion is not how good things, as while true useful! However, the river has spread this sentence is called: people understand the cycle, God understand recursion. So don't underestimate the recursive function, many people have been stopped outside the threshold of the great God for so many years, because they failed to comprehend the true meaning of recursion. And then many of the algorithms we learn will have a relationship to recursion. Come, only learn to have capital to abandon!

Back to Top

Talk about recursion again.

Here we are going to give an example of what recursion can do.

Example one:

Now you ask me, Alex, how old is the teacher? I said I wouldn'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? Egon said, I do not tell you, but I am a tournament sir two years old.

You asked Sir Wu, and the officer did not tell you, he said he was two years older than Jinxin.

Then you ask Jinxin, Jinxin told you, he is 40 ...

Did you know that at this time? How old is Alex?

1 Jinxin 40
2 Sir Wu 42
3 Egon 44
4 Alex 46

Why would you know that?

First of all, you asked Alex's age, and found Egon, Wu Sir, jinxin, you asked ask the past, until you get an exact answer, and then follow this line to find back, only to get the final Alex's age. This process is already very close to recursive thinking. We'll come to the concrete I analyze the rules between these few people.

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

So what should we do with our function in such a situation?

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

Back to Top

Recursive functions and level three menus

menu = {' Beijing ': {' Haidian ': {' Five crossing ': {' Soho ': {}, ' NetEase ': {}, ' Google ': {}            },            ' Zhongguancun ': {                ' Iqiyi ': {}, ' Autohome ': {},                ' Youku ': {},            },            ' On the ground ': {                ' Baidu ': {},            },        },        ' Changping ': {            ' Shahe ': {                ' old boy ': {},                ' Beihang ': {},            },            ' Tian Tong Yuan ': {},            ' Huilongguan ': {},        },        ' Chaoyang ': {},        ' Dongcheng ': {},    },    ' Shanghai ': {' Minhang ': {' People's Square ': {                ' Fried Chicken Shop ': {}}        ,        ' Zhabei ': ' The '            Train War ': '                Ctrip ' : {}            }        ,        ' Pudong ': {},    },    ' Shandong ': {},}
Menu
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         elif (not Dic.get (key)) or (not Dic[key]):             continue11 Threelm (menu)

python--recursive function--Jingliyang

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.