Recursion, one of Python functional programming techniques

Function recursion

The programming technique of function calling itself is called recursion.

You can call other functions inside the function, and of course you can also call yourself inside the function.

Characteristics of recursion

  • The code inside the function is the same, but the processing results are different for different parameters.
  • When the parameters meet a condition, the function is no longer executed. This is very important and is usually called a recursive exit, otherwise an endless loop will occur.

Sample code:

def sum_numbers(num):

    print(num)
    # 递归的出口很重要,否则会出现死循环
    if num == 1:
        return
    # 自己调用自己
    sum_numbers(num - 1)

sum_numbers(3)
# 3
# 2
# 1

Recursive call diagram

Recursion is divided into two important stages: recursion + backtracking.

  • Recursion: The function continuously reduces the problem size until the final termination condition.
  • Backtracking: After getting the final clear value, return to the last call for processing until the initial level.

Since unlimited recursive calls will take up a lot of memory, python limits the depth of recursive calls to functions. When the number of recursive calls reaches the limit, an exception will be thrown. To avoid this situation, the recursive call must be terminated when a certain condition is met.

Recursive case

Requirements: Calculate the accumulation of numbers, receive an integer parameter of num, and calculate the result of 1 + 2 +… num.

def sum_numbers(num):

    if num == 1:
        return 1

    # 假设 sum_numbers 能够完成 num - 1 的累加
    temp = sum_numbers(num - 1)

    # 函数内部的核心算法就是两个数字的相加
    return num + temp

print(sum_numbers(2))
# 3

Recursion is a programming technique, and it will feel a bit difficult to get in touch with it for the first time!

When dealing with uncertain loop conditions, it is particularly useful to use recursion, such as traversing the entire file directory structure.


The pilgrimage of programming

Guess you like

Origin blog.csdn.net/beyondamos/article/details/108122489