递归
- 函数直接或者间接的调用自己
阶乘
def fun0(n): print(n) if n == 1: return 1 else: return n * fun0(n-1) print(fun0(5))
非彼拉切数列
def fun1(n): if n == 1 or n == 2: return 1 else: return fun1(n-2) + fun1(n-1) x_fun1 = 5 print("斐波拉且数列的第 {h} 个数是 {w}".format(h = x_fun1, w = fun1(x_fun1))) print("斐波拉且数列的第 %d 个数是 %d" % (x_fun1, fun1(x_fun1)))
汉诺塔
def hnt(a, b, c, n): if n == 1: print("{} --> {}".format(a, c)) elif n == 2: print("{} --> {}".format(a, b)) print("{} --> {}".format(a, c)) print("{} --> {}".format(b, c)) else: hnt(a, c, b, n-1) print("{} --> {}".format(a, c)) hnt(b, a, c, n-1) hnt_a = "A" hnt_b = "B" hnt_c = "C" hnt(hnt_a, hnt_b, hnt_c, 3)
来源:https://www.cnblogs.com/TK-tank/p/12345730.html