Definition of Python recursive function and a few small examples

recursive function

(1) What is a recursive function?

We all know that a function can call other functions. If the function internally calls itself, then the function is called a recursive function.

(2) The role of recursive functions

As an example, let's calculate the factorial n! = 1 * 2 * 3 * ... * n

#不使用递归的方法:
n=4      #求4的阶乘
result=1
i=1
while i<=4:
    result=result*i
    i+=1

print(result)

#使用递归的方法:
def test1(n):#定义函数来计算数字n的阶乘
    if n==1:
        return 1
    return n * test1(n-1)

print(test1(5))
#1在函数的内部调用自己本身
#2递归函数本质是一个方法的循环调用,注意:有可能出现死循环
#3一定要定义递归的边界(什么时候退出循环)

The output is:

 24
 120
 [Finished in 0.4s]

From the comparison of the above two methods, it can be seen that the effect of the recursive function is the same as that of the loop method, that is, the recursive function is essentially a cyclic call of a method. Note: there may be an infinite loop. Therefore, when using recursive functions, be sure to define the recursion bounds (i.e. when to exit the loop).

Another case of recursive functions is the Fibonacci sequence.

Fibonacci sequence: 1, 1, 2, 3, 5, 8, 13. . . (In this sequence, there are n numbers, starting from the third number: value = previous number + previous number)

That is, n=(n-2)+(n-1)

def get_num(n):#获取斐波拉契数列中第n个数字的值
    if n==1 or n==2:
        return 1
    return get_num(n-1) + get_num(n-2)

#把获取的斐波拉契数字存放到列表中
nums=[]
for i in range(1,21):
    nums.append(get_num(i))#get_num获得一个斐波拉契数字

print(nums)

The output is:

 [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765]
 [Finished in 0.4s]

The above two cases are classic cases of recursive functions, and you need to remember how to use them. Note: In actual use, recursive functions are rarely used due to their long time consumption (compared to for loops and while loops).

Guess you like

Origin blog.csdn.net/m0_67575344/article/details/124283805