递归: 函数自己调用自己

常规阶乘


    阶乘
    5的阶乘 5 * 4 * 3 * 2* 1

    第一次循环 :
    i = 1 result = 1

    第二次循环:
    i = 2 result = 2 * 1
    result 2

    第三次循环:
    i = 3 result = 2 * 1 * 3
    result = 6

    第四次循环
    i = 4 result = 2 * 1 * 3 * 4
    result = 24

    第五次循环
    i = 5 result = 2 * 1 * 3 * 4 * 5
    result = 120

什么时候可以用递归:
当你不确定循环的个数的时候,可以使用递归,只需要你定义什么时候结束就可以了


def test(num):
    i = 1
    result = 1
    while i <= num:
        result *= i
        i+=1
    return result
test(5)

递归计算5的阶乘


def test(num):
    if num > 1:
        return num * test(num - 1)
    else:
        return num
test(5)

递归拆解


def test4(): # 第五次,将值1返回给上次
    return 1
def test3(): # 第四次,将值2返回给上次
    return 2 * test4()
def test2(): # 第三次,将值6返回给上次
    return 3 * test3(),
def test1(): # 第二次将值24返回给上次
    return 4 * test2(),
def test(): # 第一次,接收第二次的返回值24,返回5*24=120
    return 5 * test1()
print(test())

递归解析

image

posted on 2022-03-25 21:16  风中的琥珀  阅读(64)  评论(0)    收藏  举报