Usage of python recursive function

def fact(n):
    if n==1:
        return 1
    return n * fact(n - 1)

The use of recursive functions can simplify the program, but at the same time face the problem of possible stack overflow

The solution is: 

The way to solve the recursive call stack overflow is through tail recursion optimization. In fact, the effect of tail recursion and loop is the same, so it is also possible to regard loop as a special tail recursive function.

Tail recursion means that when the function returns, it calls itself, and the return statement cannot contain expressions. In this way, the compiler or interpreter can optimize the tail recursion, so that no matter how many times the recursion itself is called, it only occupies one stack frame, and there will be no stack overflow.

def fact(n):
    return fact_iter(n, 1)

def fact_iter(num, product):
    if num == 1:
        return product
    return fact_iter(num - 1, num * product)

Solve the Tower of Hanoi problem! Picture source network

Recursion-Tower of Hanoi Problem-Algorithm-Xiaoxiang Blog

The rule is: only the smaller plate can be placed on the larger plate, and all the plates are arranged on C according to the size. Recursive thinking can be used to solve this problem.

Positive understanding: To move n blocks from A to C

Divided into 3 steps,

n-1 block moved from A to B

Move the last block from A to C

n-1 block from B to C

Below is the code for the three towers of Hanoi

def move(n, a, b, c):
    if n == 1:
        print('move', a, '-->', c)
    else:
        move(n-1, a, c, b)
        move(1, a, b, c)
        move(n-1, b, a, c)

move(4, 'A', 'B', 'C')

 Reference source: https://www.liaoxuefeng.com/wiki/1016959663602400/1017268131039072

Guess you like

Origin blog.csdn.net/li4692625/article/details/109482683