Python study notes three: recursive operations, to achieve Fibonacci sequence and Tower of Hanoi

Recursive operation

  • Recursion: the function calls itself indirectly or directly
  • Recursion is divided into two processes:
    • 1. The process of calling down and decomposing
    • 2. Back up, the process of synthesis
  • Recursion needs attention:
    • There must be an end condition***
  • Using recursive operation will make the program very simple and concise
  • Algorithms that trade resources for writing speed
def funa(n):
    print("this is amy")

def funcb(n):
    funa(100)
    print("this is csc")
    
funcb(100)

this is amy
this is csc

# fun_a 表示计算阶乘:f(n)=n*f(n-1),n>1

def fun_a(n):
    print(n)
    # 此为结束条件n=1
    if n == 1:
        return 1
    return n * fun_a(n-1)

rst = fun_a(5)
print("f(10) = ", rst)

# 若无结束条件,将无限递归下去,出现RecursionError(递归错误)

5
4
3
2
1
f(10) = 120

Fibonacci sequence

  • Mathematical definition: f(n) = f(n-1) + f(n-2), n>2, both the first and second digits are: 1
def fib(n):
    if n ==1 or n == 2:
        return 1
    return fib(n-1) + fib(n-2)

rst = fib(10)
print("rst = ", rst)

rst = 55

Tower of Hanoi

  • There are three pillars A, B, and C. There are three plates on A. It is stipulated that the big plate must be below each time. Finally, the three plates are moved to the top of C.
a, b, c = "A", "B", "C"
def hano(a,b,c,n):
    if n == 1:
        print("{} -> {}".format(a,c))
        return None
    
    if n == 2:
        print("{} -> {}".format(a,c))
        print("{} -> {}".format(a,b))
        print("{} -> {}".format(b,c))
        return None
    
    # 将n-1个盘子,借助于c塔移动到b塔上
    hano(a,c,b,n-1)
    print("{} -> {}".format(a,c))
    hano(b, a, c, n-1)
#只有一个盘子
hano(a, b, c, 1)
print()

# 有三个盘子
hano(a, b, c, 3)

A -> C

A -> B
A -> C
C -> B
A -> C
B -> C
B -> A
A -> C

Guess you like

Origin blog.csdn.net/amyniez/article/details/104363472
Recommended