recursive function

Inside a function, other functions can be called. A function is recursive if it internally calls itself.

For example, let's calculate the factorial n! = 1 x 2 x 3 x ... x n, expressed as a function fact(n), we can see that:

fact(n) = n! = 1 x 2 x 3 x ... x (n-1) x n = (n-1)! x n = fact(n-1) x n

Therefore, fact(n)it can be expressed as n x fact(n-1), only when n=1 needs special processing.

So, fact(n)it can be written recursively as:

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

If we calculate fact(5), we can see the calculation process as follows according to the function definition:

===> fact(5)
===> 5 * fact(4)
===> 5 * (4 * fact(3))
===> 5 * (4 * (3 * fact(2)))
===> 5 * (4 * (3 * (2 * fact(1))))
===> 5 * (4 * (3 * (2 * 1)))
===> 5 * (4 * (3 * 2))
===> 5 * (4 * 6)
===> 5 * 24
===> 120

使用递归函数需要注意防止栈溢出。在计算机中,函数调用是通过栈(stack)这种数据结构实现的,每当进入一个函数调用,栈就会加一层栈帧,每当函数返回,栈就会减一层栈帧。由于栈的大小不是无限的,所以,递归调用的次数过多,会导致栈溢出

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324705326&siteId=291194637