Home > Backend Development > Python Tutorial > Demystifying Python Recursion

Demystifying Python Recursion

Lisa Kudrow
Release: 2025-03-05 09:57:11
Original
555 people have browsed it

Demystifying Python Recursion

In Python programming, many complex tasks can be broken down into simpler subtasks. Recursion is a powerful way to implement this decomposition, making the code more concise and easier to maintain. This tutorial will cover the concepts of recursion, the advantages, and how to use it in Python.

What is recursion?

Recursion is a way to solve a problem by solving a smaller instance of the problem. This approach can be applied to many challenges in programming.

Advantages of using recursion

Some of the advantages of using recursion include:

  • Simplify code writing and make it easier to debug.
  • Reduce the algorithm run time (as a function of input length).
  • More effective when solving very complex problems (especially those based on tree structures).

Beginner of Python recursive functions

Recursion may seem complicated, but it is not. Simply put, suppose you have two rectangles A and B. Add them together to form a rectangle C. This is a recursive process in itself. We use smaller instances of rectangles to define ourselves, if we want to write Python functions, it looks like this:

def rectangle(a, b):
    return a + b
Copy after login
Copy after login

Since the recursive function calls itself, a rule or breakpoint is needed to terminate the process or loop. This condition is called the benchmark condition. Each recursive program requires a benchmark condition, otherwise the process will result in an infinite loop.

The second requirement is the recursive case, that is, the function call itself.

Let's take an example:

In this example, you will write a factorial function that takes an integer (positive number) as input. A factorial for a number is obtained by multiplying the number by all positive integers below it. For example, factorial(3) = 3 x 2 x 1, factorial(2) = 2 x 1, factorial(0) = 1.

First define the benchmark case, that is, factorial(0) = 1.

As shown above, there is a relationship between each successive factorial scene. You should notice factorial(4) = 4 x factorial(3). Similarly, factorial(5) = 5 x factorial(4).

The second part will write a function that calls itself.

After simplifying, the generated function will be:

def factorial(n):
    # 定义基准情况
    if n == 0:
        return 1
    else:
        return n * factorial(n - 1)

print(factorial(5))

# 结果
# 120
Copy after login
Copy after login

If n==0, the solution is:

def factorial(n):
    # 定义基准情况
    if n == 0:
        return 1
    else:
        return n * factorial(n - 1)


print(factorial(0))

# 结果
# 1
Copy after login
Copy after login

Now that you know how to write recursive functions, let's look at a few case studies that will strengthen your understanding of recursion.

Case Study 1: Fibonacci Sequence

In the Fibonacci sequence, each number is the sum of the first two numbers, for example: 1 1 = 2; 1 2 = 3; 2 3 = 5; 3 5 = 8. The Fibonacci sequence has been applied in many areas, most commonly for Forex traders predicting stock market price trends.

Fibonacci sequences start with 0 and 1. The first number in the Fibonacci sequence is 0, the second number is 1, and the third term in the sequence is 0 1 = 1. The fourth term is 1 1 = 2, and so on.

In order to get a recursive function, you need to have two benchmark cases, namely 0 and 1. You can then convert the addition mode to the else case.

The generated function will be:

def rectangle(a, b):
    return a + b
Copy after login
Copy after login

Case Study 2: Inverting the String

In this example, you will write a function that takes a string as input and then returns an inversion of that string.

First define the benchmark case, which will check whether the string is equal to 0, and if so, the string itself is returned.

The second step is to recursively call the inversion function to slice the part of the string except the first character, and then concatenate the first character to the end of the slice string.

The generated function is as follows:

def factorial(n):
    # 定义基准情况
    if n == 0:
        return 1
    else:
        return n * factorial(n - 1)

print(factorial(5))

# 结果
# 120
Copy after login
Copy after login

Case Study 3: Sum of Elements

In this example, you will write a function that takes an array as input and then returns the sum of elements in the list.

First define the benchmark case, which will check whether the size of the list is zero, and if true, return 0.

The second step returns the element and the call to the function sum(), subtracting an element of the list.

The solution is as follows:

def factorial(n):
    # 定义基准情况
    if n == 0:
        return 1
    else:
        return n * factorial(n - 1)


print(factorial(0))

# 结果
# 1
Copy after login
Copy after login

The solution to the empty list is as follows:

def fibonacci(n):
    # 定义基准情况 1
    if n == 0:
        return 0
    # 定义基准情况 2
    elif n == 1:
        return 1
    else:
        return fibonacci(n - 1) + fibonacci(n - 2)

print(fibonacci(5))

# 结果为 5
Copy after login

Conclusion

This tutorial describes what you need to solve complex programs in Python using recursion. It should also be noted that recursion also has its own limitations:

  • Recursively occupy a lot of stack space, making it slow to maintain the program.
  • Recursive functions require more space and time to execute.
  • Recursive functions can become complicated and difficult to debug.

This thumbnail image is generated using Open AI DALL-E.

The above is the detailed content of Demystifying Python Recursion. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template