廖雪峰 | 3.2 递归函数

2022-04-16  本文已影响0人  苦哈哈的柠檬水

1,定义
一个函数在内部调用自身本身,这个函数就是递归函数。
例如,计算阶乘n! = 1 x 2 x 3 x ... x n

>>> def fact(n):
...     if n == 1:
...         return 1
...     return n*fact(n-1)
...
>>> fact(1)
1
>>> fact(3)
6

2,栈溢出
(1)栈溢出,stack overflow,递归调用的次数过多,会导致栈溢出。例如,fact(1000)

>>> fact(1000)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 4, in fact
  File "<stdin>", line 4, in fact
  File "<stdin>", line 4, in fact
  [Previous line repeated 995 more times]
  File "<stdin>", line 2, in fact
RecursionError: maximum recursion depth exceeded in comparison

(2)尾递归优化,是解决递归调用栈溢出的方法。

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)

fact(100)#依旧报错
# -*- coding: utf-8 -*-
def hanoi(n, a, b, c):
    if n == 1:
        print(a, '-->', c)
    else:
        hanoi(n-1, a, b, c)
        print(a, '-->', c)
        hanoi(n-1, b, a, c)

#测试
>>> from hanoi import hanoi
>>> hanoi(3, 'A', 'B', 'C')
A --> C
A --> C
B --> C
A --> C
B --> C
B --> C
A --> C
上一篇 下一篇

猜你喜欢

热点阅读