python-recursive function

Source: Internet
Author: User

Read the catalogue:

  1. Function Execution Flow

  2. Recursive recursion

  3. Recursive exercises

Content:

1. Function Execution Flow

Http://pythontutor.com/visualize.html#mode=display # on this site you can enter the code to view the demo
or pycharm Debug View frames
1 defFoo1 (b, b1=3):2     Print('Foo1 called', B, B1)3 defFoo2 (c):4 Foo3 (c)5     Print('Foo2 called', c)6 defFoo3 (d):7     Print('Foo3 called', D)8     9 defMain ():Ten     Print('Main called') OneFOO1 (100, 101) AFoo2 (200) -     Print('Main ending') -      the Main () -------------------------------------------------- - Main called -Foo1 called 100 101 +Foo3 called 200 -Foo2 called 200 +Main ending

 Make a simple description of the above execution process:

      1. Generate Foo1,foo2, Foo3,main function object in global frame
      2. Main function call
      3. In main, look for the built-in function print stack , press the constant string stack, call the function, pop up the top of the stack.
      4. Main in the global lookup function foo1 stack, the constant 100, 101 compression stack, call function foo1, create a stack frame. The print function presses the stack, string and variable B, b1 the stack, invokes the function, pops the top of the stack, and returns the value.
      5. Main in the global Find Foo2 function pressure stack, will be constant 200, press stack, call Foo2, create stack frame. The FOO3 function presses the stack, the variable c references the stack, invokes the Foo3, creates the stack frame, Foo3 completes the print function call, returns, Foo2 resumes the call, executes the print, returns the value, main in the FOO2 call ends the popup stack top, main continues to execute the print function call, pops up the top of the stack , main returns.

Figure 1, the function reads into memory

Figure 2: Stack frame graph when calling Foo2 (200) When executing the main function

Note:

      • function execution to press the stack, functions within the execution of functions, the inner layer function to fall on the outer layer function.
      • The function ends to pop up, including the parameters required by the function and so on.
      • Stack is thread-dependent
        • Define a function, two threads call the function, respectively, in their own stack space, each thread does not affect each other.
      • So from here you can see the local variable is created when it is called, the end of the call is dead (when the call is pressed, it pops up at the end, and the local variable is not referenced)

  Note:

1 def fn (a): 2     Print (a) 3 4 g = [1]  5  6fn (g)  7  8#  Popup extinction just A, not G, if the reference type, just address, as above 9#  In fact, g= "1" is put in the heap, open up memory space, by GC management  # stack just put reference address

2. Recursive recursion

    • A function that calls itself directly or indirectly is recursive.
    • Recursion requires a boundary condition, a recursive forward segment, and a recursive return segment.
    • There must be a boundary condition for recursion.
    • Recursive progression when boundary conditions are not met
    • When the boundary conditions are met, the recursion returns.

  2.1: Fibonacci sequence: 1,1,2,3,5,8,13 ... 

1---------------------Fibonacci Sequence2 #No1 The most initial version is done with a for loop, swapping3 deffib (n):4A =05b = 16      forIinchrange (n):7A, B = B, A +b8     returna9 Print(FIB (3))#2Ten  One #no2.1 uses recursion to complete, but this version of the recursive efficiency is very low, through the Ipython jupyter%%timeit test, is not as good as the loop. Because the return of the FIB (n-1) +fib (n-2), D is to continue to execute separately, the amount of data is large, this is the equivalent of a lot of repetition, the front of it, the back of the FIB (n-2) to be counted once, so the efficiency is very low.  A deffib (n): -     ifN < 3: -         return1 the     returnFIB (n-1) + fib (n-2) -  - Print(FIB (3))#2 -  + #no2.2 Variant version: - deffib (n): +     return1ifN < 3ElseFIB (n-1) + fib (n-2) A  at Print(FIB (3))#2 -  - #No 3 recursion with the last result - #The default parameter is used as the result of the operation, and N is the number of cycles control - defFIB (n, A=0, b=1):defFIB (n, A=0, b=1):defFIB (n, a=0, b=1): -     ifn = = 0:ifn = = 0:ifn = =0: in         returnAreturnAreturna -A, B = B, A + b A, B = B, A + b A, B = B, A +b to     returnFIB (N-1, A, b)returnFIB (N-1, A, b)returnFIB (n-1, A, b) +  - Print((FIB (3)))
Fibonacci sequence recursion and the initial version implementation

  2.2: Individual interpreter protection against recursion : When you reach this data, you throw an exception, whether you want to do it or not!

In CPython:

      Import  sys
Print ((Sys.getrecursionlimit ()) # 1000

Ipython: Yes 3000

    Note: But the fact is not enough for this number, because the current stack cannot have only its own functions, which may contain other data, basic data, etc. will take up part of the stack space.

   Recursive requirements:

        • Recursion must have exit conditions, recursive calls must be executed to this exit condition. A recursive call without an exit condition is an infinite invocation.
        • The depth of recursive calls should not be too deep
          • Python limits the depth of recursive calls to protect the interpreter
          • exceeds recursion depth limit, throws Recursionerror:maxinum recursion depthexceeded exceeds maximum depth
          • Sys,getrecursionlimit ()

    Recursive performance:

        • For loop, recursive performance comparison, in fact, the performance of the For loop is better than recursive performance, especially when the volume of data is large.
        • The loop is slightly more complex, but as long as it is not a dead loop, it can be iterated multiple times until the result is calculated
        • The FIB function code is simple and easy to understand, but only to get to the mouth of the crooked layer of function calls, internal recursive results are the results of the case, and given a n are to be 2n recursion, depth, efficiency at the end of the month, in order to obtain the Fibonacci sequence outside in a set of n cycles, efficiency is lower, However, the space complexity of the for loop is relatively high.
        • Recursive return has a depth limit, if the recursive complex, function repeatedly pressure stack, stack memory quickly overflow.

   Inter-node recursion:

Def foo1 ():

Foo2 ()

Def foo2 ():

Foo1 ()

Foo1 ()

Indirect recursion, which calls the function itself through another function

However, it is very dangerous to make a cyclic recursive call, but it is often the case that this kind of invocation can occur in the case of code complexity, to avoid the recurrence of this recursive invocation with the specification of the code.

    Recursive Summary:

        • Recursion is a natural expression that fits logical thinking.
        • Recursive relative running efficiency is low, each call function to open up the stack frame, each time to press the stack, but the efficiency is low.
        • Recursion has a depth limit, and if the recursive hierarchy is too deep and the function repeatedly presses the stack, the stack memory quickly overflows.
        • If it is a finite number of recursion, recursive calls can be used, or loop substitution is used, the loop code is slightly more complicated, but as long as it is not the West Sun Yu can iterate until the result is calculated.
        • The vast majority of recursion can be implemented using loops.
        • On the line, can not do without.

3. Recursive exercises

Https://www.cnblogs.com/JerryZao/p/9531951.html

python-recursive function

Related Article

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.