Functional Programming Python - recursive

Functional Programming Python - recursive

Constantly seeking 100 divided by 2 until the quotient is zero so far, in addition to print each quotient

Cyclic achieve:

n = 100
while n > 0:
    n = int(n/2)
    print(n)

Output:

50
25
12
6
3
1
0

If you use the function, how to achieve it?

def calc(n):
    n = int(n/2)
    print(n)
    if n > 0:
        calc(n)    # 调用自己
calc(100)

Inside the function, you can call other functions. If a function is called internally self in itself, this function is called recursive functions. This code we wrote above is recursive.

Recursive implementation process

def calc(n):
    n = int(n/2)
    print(n)
    if n > 0:
         calc(n)
    print(n) 
calc(10)

Output:

5

2

1

0

0

1

2

5

Why the output would be like this?

As shown above, when each function into the next layer, the current layer is not the end of the function, it must continue to go to the next level and so it calls the function returns the execution end down. So will execute when the bottom of the function phrase print (n) will wait for the innermost layer of the execution, and then continue out back layer, so the effect 0,1,2,5 will appear.

Recursive nature:

1, must have a clear end condition.

2, each time deeper into the recursive, recursive problem size should be reduced compared to last.

3, the recursive efficiency is not high, too much will cause the level of recursion stack overflow (in the computer, the function call is achieved through the stack (Stack) This data structure, each time a function call into the stack the stack frame is increased by one whenever the function returns, the stack will cut a layer stack frame. Since the stack size is not unlimited, so the number of recursive calls too much will result in a stack overflow).

Recursion in a particular scene is quite useful, after some algorithms have to learn to use recursion, such as heap row, row and so fast.

Guess you like

Origin www.cnblogs.com/Kwan-C/p/11529602.html