python algorithm illustration - knowledge

1. recursion and cycles

If you use a loop, program performance may be higher; if you use recursion, the program may be easier to understand, so that the outcome of the program more clearly, but there is no performance advantage. Recursive function in a loop that calls itself, is that while for the cycle and so on.

2. Recursion

There are two parts recursive, recursive baseline conditions and conditions, conditions of the recursive call itself refers to a function, and refers to the baseline conditions is no longer a function calls itself, so as to avoid an infinite loop.

3. Stack

There are two general stack operation: press-fitted (inserted), and the pop-up (deleting and read).
All function calls into the call stack. Call stack can be long, it will take up a lot of memory.
Although it is convenient to use the stack, but it comes at a price: storing detailed information can take up a lot of memory. Each function call must occupy a certain memory, if the stack is high, it means that the computer stores information about a large number of function calls. In this case, you have two options.
 rewrite the code, instead using loops.
 using tail recursion. This is an advanced recurrent theme. In addition, not all languages support tail recursion.

Guess you like

Origin blog.csdn.net/xili2532/article/details/90897132