Hướng dẫn how recursion works in python? - cách đệ quy hoạt động trong python?

Trong hướng dẫn này, bạn sẽ học cách tạo một hàm đệ quy (một hàm tự gọi).

Đệ quy là gì?

Đệ quy là quá trình xác định một cái gì đó theo chính nó.

Một ví dụ thế giới vật lý sẽ là đặt hai gương song song đối diện nhau. Bất kỳ đối tượng ở giữa chúng sẽ được phản ánh đệ quy.


Chức năng đệ quy Python

Trong Python, chúng ta biết rằng một hàm có thể gọi các chức năng khác. Thậm chí có thể cho chức năng gọi chính nó. Các loại cấu trúc này được gọi là các hàm đệ quy.

Hình ảnh sau đây cho thấy hoạt động của một hàm đệ quy gọi là recurse.

Hướng dẫn how recursion works in python? - cách đệ quy hoạt động trong python?
Chức năng đệ quy trong Python

Sau đây là một ví dụ về hàm đệ quy để tìm giai thừa của một số nguyên.

Factorial của một số là sản phẩm của tất cả các số nguyên từ 1 đến số đó. Ví dụ: giai thừa của 6 (ký hiệu là 6!) Là 1*2*3*4*5*6 = 720.

Ví dụ về hàm đệ quy

def factorial(x):
    """This is a recursive function
    to find the factorial of an integer"""

    if x == 1:
        return 1
    else:
        return (x * factorial(x-1))


num = 3
print("The factorial of", num, "is", factorial(num))

Đầu ra

The factorial of 3 is 6

Trong ví dụ trên,

The factorial of 3 is 6
0 là một hàm đệ quy như nó tự gọi.

Khi chúng ta gọi hàm này với số nguyên dương, nó sẽ tự gọi mình bằng cách giảm số.

Mỗi hàm nhân số số với giai thừa của số bên dưới nó cho đến khi nó bằng một. Cuộc gọi đệ quy này có thể được giải thích trong các bước sau.

factorial(3)          # 1st call with 3
3 * factorial(2)      # 2nd call with 2
3 * 2 * factorial(1)  # 3rd call with 1
3 * 2 * 1             # return from 3rd call as number=1
3 * 2                 # return from 2nd call
6                     # return from 1st call

Chúng ta hãy xem một hình ảnh hiển thị một quá trình từng bước về những gì đang diễn ra:

Hướng dẫn how recursion works in python? - cách đệ quy hoạt động trong python?
Làm việc của một chức năng giai thừa đệ quy

Đệ quy của chúng tôi kết thúc khi số lượng giảm xuống 1. cái này được gọi là điều kiện cơ sở.

Mỗi chức năng đệ quy phải có một điều kiện cơ sở dừng đệ quy hoặc nếu không thì hàm tự gọi chính nó.

Thông dịch viên Python giới hạn độ sâu của đệ quy để giúp tránh các đệ quy vô hạn, dẫn đến tràn chồng.

Theo mặc định, độ sâu tối đa của đệ quy là 1000. Nếu giới hạn được vượt qua, nó sẽ dẫn đến

The factorial of 3 is 6
1. Hãy nhìn vào một điều kiện như vậy.

def recursor():
    recursor()
recursor()

Đầu ra

Traceback (most recent call last):
  File "", line 3, in 
  File "", line 2, in a
  File "", line 2, in a
  File "", line 2, in a
  [Previous line repeated 996 more times]
RecursionError: maximum recursion depth exceeded

Trong ví dụ trên, The factorial of 3 is 60 là một hàm đệ quy như nó tự gọi.

  1. Khi chúng ta gọi hàm này với số nguyên dương, nó sẽ tự gọi mình bằng cách giảm số.
  2. Mỗi hàm nhân số số với giai thừa của số bên dưới nó cho đến khi nó bằng một. Cuộc gọi đệ quy này có thể được giải thích trong các bước sau.
  3. Chúng ta hãy xem một hình ảnh hiển thị một quá trình từng bước về những gì đang diễn ra:

Làm việc của một chức năng giai thừa đệ quy

  1. Đệ quy của chúng tôi kết thúc khi số lượng giảm xuống 1. cái này được gọi là điều kiện cơ sở.
  2. Mỗi chức năng đệ quy phải có một điều kiện cơ sở dừng đệ quy hoặc nếu không thì hàm tự gọi chính nó.
  3. Thông dịch viên Python giới hạn độ sâu của đệ quy để giúp tránh các đệ quy vô hạn, dẫn đến tràn chồng.

Xem thảo luận

Cải thiện bài viết

Lưu bài viết

  • Đọc
  • Bàn luận
  • Xem thảo luận

    Cải thiện bài viết

    Lưu bài viết

    Đọc

    Hướng dẫn how recursion works in python? - cách đệ quy hoạt động trong python?
    Advantages of using recursion

    • Bàn luận
    • Thuật ngữ đệ quy có thể được định nghĩa là quá trình xác định một cái gì đó theo chính nó. Nói một cách đơn giản, đó là một quá trình trong đó một hàm tự gọi trực tiếp hoặc gián tiếp. Ưu điểm của việc sử dụng đệ quy
    • Một chức năng phức tạp có thể được chia thành các vấn đề phụ nhỏ hơn sử dụng đệ quy.

    Tạo trình tự đơn giản hơn thông qua đệ quy hơn là sử dụng bất kỳ lần lặp lồng nhau nào.

    • Các hàm đệ quy hiển thị mã trông đơn giản và hiệu quả.
    • Nhược điểm của việc sử dụng đệ quy
    • Rất nhiều bộ nhớ và thời gian được thực hiện thông qua các cuộc gọi đệ quy làm cho nó tốn kém để sử dụng.

    Syntax:

    def func(): <--
                  |
                  | (recursive call)
                  |
        func() ----

    Các chức năng đệ quy là một thách thức để gỡ lỗi. A Fibonacci sequence is the integer sequence of 0, 1, 1, 2, 3, 5, 8…. 

    Python3

    Lý do đằng sau đệ quy đôi khi có thể khó khăn để suy nghĩ qua.

    Ví dụ 1: Trình tự Fibonacci là trình tự số nguyên là 0, 1, 1, 2, 3, 5, 8. & NBSP;

    The factorial of 3 is 6
    2
    The factorial of 3 is 6
    3

    The factorial of 3 is 6
    4
    factorial(3)          # 1st call with 3
    3 * factorial(2)      # 2nd call with 2
    3 * 2 * factorial(1)  # 3rd call with 1
    3 * 2 * 1             # return from 3rd call as number=1
    3 * 2                 # return from 2nd call
    6                     # return from 1st call
    4
    The factorial of 3 is 6
    9

    The factorial of 3 is 6
    4
    The factorial of 3 is 6
    5
    The factorial of 3 is 6
    6
    The factorial of 3 is 6
    7
    The factorial of 3 is 6
    8
    The factorial of 3 is 6
    9

    factorial(3)          # 1st call with 3
    3 * factorial(2)      # 2nd call with 2
    3 * 2 * factorial(1)  # 3rd call with 1
    3 * 2 * 1             # return from 3rd call as number=1
    3 * 2                 # return from 2nd call
    6                     # return from 1st call
    0
    factorial(3)          # 1st call with 3
    3 * factorial(2)      # 2nd call with 2
    3 * 2 * factorial(1)  # 3rd call with 1
    3 * 2 * 1             # return from 3rd call as number=1
    3 * 2                 # return from 2nd call
    6                     # return from 1st call
    1
    factorial(3)          # 1st call with 3
    3 * factorial(2)      # 2nd call with 2
    3 * 2 * factorial(1)  # 3rd call with 1
    3 * 2 * 1             # return from 3rd call as number=1
    3 * 2                 # return from 2nd call
    6                     # return from 1st call
    2

    Các

    The factorial of 3 is 6
    4
    Traceback (most recent call last):
      File "", line 3, in 
      File "", line 2, in a
      File "", line 2, in a
      File "", line 2, in a
      [Previous line repeated 996 more times]
    RecursionError: maximum recursion depth exceeded
    6
    Traceback (most recent call last):
      File "", line 3, in 
      File "", line 2, in a
      File "", line 2, in a
      File "", line 2, in a
      [Previous line repeated 996 more times]
    RecursionError: maximum recursion depth exceeded
    7
    Traceback (most recent call last):
      File "", line 3, in 
      File "", line 2, in a
      File "", line 2, in a
      File "", line 2, in a
      [Previous line repeated 996 more times]
    RecursionError: maximum recursion depth exceeded
    8
    Traceback (most recent call last):
      File "", line 3, in 
      File "", line 2, in a
      File "", line 2, in a
      File "", line 2, in a
      [Previous line repeated 996 more times]
    RecursionError: maximum recursion depth exceeded
    9

    factorial(3)          # 1st call with 3
    3 * factorial(2)      # 2nd call with 2
    3 * 2 * factorial(1)  # 3rd call with 1
    3 * 2 * 1             # return from 3rd call as number=1
    3 * 2                 # return from 2nd call
    6                     # return from 1st call
    4
    The factorial of 3 is 6
    9

    The factorial of 3 is 6
    4
    Traceback (most recent call last):
      File "", line 3, in 
      File "", line 2, in a
      File "", line 2, in a
      File "", line 2, in a
      [Previous line repeated 996 more times]
    RecursionError: maximum recursion depth exceeded
    6
    Traceback (most recent call last):
      File "", line 3, in 
      File "", line 2, in a
      File "", line 2, in a
      File "", line 2, in a
      [Previous line repeated 996 more times]
    RecursionError: maximum recursion depth exceeded
    7
    def func(): <--
                  |
                  | (recursive call)
                  |
        func() ----
    5
    Traceback (most recent call last):
      File "", line 3, in 
      File "", line 2, in a
      File "", line 2, in a
      File "", line 2, in a
      [Previous line repeated 996 more times]
    RecursionError: maximum recursion depth exceeded
    9

    def recursor():
        recursor()
    recursor()
    7
    The factorial of 3 is 6
    7
    def recursor():
        recursor()
    recursor()
    9

    Fibonacci series:
    0
    1
    1
    2
    3
    5
    8
    13
    21
    34
    
    2
    Traceback (most recent call last):
      File "", line 3, in 
      File "", line 2, in a
      File "", line 2, in a
      File "", line 2, in a
      [Previous line repeated 996 more times]
    RecursionError: maximum recursion depth exceeded
    6
    Fibonacci series:
    0
    1
    1
    2
    3
    5
    8
    13
    21
    34
    
    4

    The factorial of 3 is 6
    5
    Traceback (most recent call last):
      File "", line 3, in 
      File "", line 2, in a
      File "", line 2, in a
      File "", line 2, in a
      [Previous line repeated 996 more times]
    RecursionError: maximum recursion depth exceeded
    1
    The factorial of 3 is 6
    7
    Traceback (most recent call last):
      File "", line 3, in 
      File "", line 2, in a
      File "", line 2, in a
      File "", line 2, in a
      [Previous line repeated 996 more times]
    RecursionError: maximum recursion depth exceeded
    3
    The factorial of 3 is 6
    9

    Fibonacci series:
    0
    1
    1
    2
    3
    5
    8
    13
    21
    34
    

    Output:

    Fibonacci series:
    0
    1
    1
    2
    3
    5
    8
    13
    21
    34

    def func(): <--
                  |
                  | (recursive call)
                  |
        func() ----
    7
    def func(): <--
                  |
                  | (recursive call)
                  |
        func() ----
    8
    def func(): <--
                  |
                  | (recursive call)
                  |
        func() ----
    9
    Fibonacci series:
    0
    1
    1
    2
    3
    5
    8
    13
    21
    34
    
    0
    Fibonacci series:
    0
    1
    1
    2
    3
    5
    8
    13
    21
    34
    
    1
    The factorial of 6 is denoted as 6! = 1*2*3*4*5*6 = 720. 

    Python3

    Đầu ra

    Ví dụ 2: Factorial của 6 được ký hiệu là 6! = 1*2*3*4*5*6 = 720. & nbsp;

    The factorial of 3 is 6
    2
    The factorial of 3 is 6
    3

    The factorial of 3 is 6
    4
    factorial(3)          # 1st call with 3
    3 * factorial(2)      # 2nd call with 2
    3 * 2 * factorial(1)  # 3rd call with 1
    3 * 2 * 1             # return from 3rd call as number=1
    3 * 2                 # return from 2nd call
    6                     # return from 1st call
    4
    The factorial of 3 is 6
    9

    The factorial of 3 is 6
    4
    The factorial of 3 is 6
    5
    The factorial of 3 is 6
    6
    The factorial of 3 is 6
    7
    The factorial of 3 is 6
    8
    The factorial of 3 is 6
    9

    factorial(3)          # 1st call with 3
    3 * factorial(2)      # 2nd call with 2
    3 * 2 * factorial(1)  # 3rd call with 1
    3 * 2 * 1             # return from 3rd call as number=1
    3 * 2                 # return from 2nd call
    6                     # return from 1st call
    0
    factorial(3)          # 1st call with 3
    3 * factorial(2)      # 2nd call with 2
    3 * 2 * factorial(1)  # 3rd call with 1
    3 * 2 * 1             # return from 3rd call as number=1
    3 * 2                 # return from 2nd call
    6                     # return from 1st call
    1
    factorial(3)          # 1st call with 3
    3 * factorial(2)      # 2nd call with 2
    3 * 2 * factorial(1)  # 3rd call with 1
    3 * 2 * 1             # return from 3rd call as number=1
    3 * 2                 # return from 2nd call
    6                     # return from 1st call
    2

    Các

    The factorial of 3 is 6
    4
    Traceback (most recent call last):
      File "", line 3, in 
      File "", line 2, in a
      File "", line 2, in a
      File "", line 2, in a
      [Previous line repeated 996 more times]
    RecursionError: maximum recursion depth exceeded
    6
    Traceback (most recent call last):
      File "", line 3, in 
      File "", line 2, in a
      File "", line 2, in a
      File "", line 2, in a
      [Previous line repeated 996 more times]
    RecursionError: maximum recursion depth exceeded
    7recurse8
    Traceback (most recent call last):
      File "", line 3, in 
      File "", line 2, in a
      File "", line 2, in a
      File "", line 2, in a
      [Previous line repeated 996 more times]
    RecursionError: maximum recursion depth exceeded
    9

    def recursor():
        recursor()
    recursor()
    7
    The factorial of 3 is 6
    7
    def recursor():
        recursor()
    recursor()
    9

    The factorial of 3 is 6
    4
    Traceback (most recent call last):
      File "", line 3, in 
      File "", line 2, in a
      File "", line 2, in a
      File "", line 2, in a
      [Previous line repeated 996 more times]
    RecursionError: maximum recursion depth exceeded
    6
    Traceback (most recent call last):
      File "", line 3, in 
      File "", line 2, in a
      File "", line 2, in a
      File "", line 2, in a
      [Previous line repeated 996 more times]
    RecursionError: maximum recursion depth exceeded
    7
    The factorial of 3 is 6
    09
    Traceback (most recent call last):
      File "", line 3, in 
      File "", line 2, in a
      File "", line 2, in a
      File "", line 2, in a
      [Previous line repeated 996 more times]
    RecursionError: maximum recursion depth exceeded
    9

    factorial(3)          # 1st call with 3
    3 * factorial(2)      # 2nd call with 2
    3 * 2 * factorial(1)  # 3rd call with 1
    3 * 2 * 1             # return from 3rd call as number=1
    3 * 2                 # return from 2nd call
    6                     # return from 1st call
    4
    The factorial of 3 is 6
    9

    The factorial of 3 is 6
    5
    Traceback (most recent call last):
      File "", line 3, in 
      File "", line 2, in a
      File "", line 2, in a
      File "", line 2, in a
      [Previous line repeated 996 more times]
    RecursionError: maximum recursion depth exceeded
    1
    The factorial of 3 is 6
    7
    Traceback (most recent call last):
      File "", line 3, in 
      File "", line 2, in a
      File "", line 2, in a
      File "", line 2, in a
      [Previous line repeated 996 more times]
    RecursionError: maximum recursion depth exceeded
    3
    The factorial of 3 is 6
    9

    The factorial of 3 is 6
    5
    Traceback (most recent call last):
      File "", line 3, in 
      File "", line 2, in a
      File "", line 2, in a
      File "", line 2, in a
      [Previous line repeated 996 more times]
    RecursionError: maximum recursion depth exceeded
    1
    The factorial of 3 is 6
    7
    Traceback (most recent call last):
      File "", line 3, in 
      File "", line 2, in a
      File "", line 2, in a
      File "", line 2, in a
      [Previous line repeated 996 more times]
    RecursionError: maximum recursion depth exceeded
    3
    The factorial of 3 is 6
    9

    Factorial of number 6 = 720
    

    def func(): <-- | | (recursive call) | func() ----7 def func(): <-- | | (recursive call) | func() ----8def func(): <-- | | (recursive call) | func() ----9 Fibonacci series: 0 1 1 2 3 5 8 13 21 34 0Fibonacci series: 0 1 1 2 3 5 8 13 21 34 1

    Đầu raIs it possible to optimize a program by making use of a tail-recursive function instead of non-tail recursive function? Considering the function given below in order to calculate the factorial of n, we can observe that the function looks like a tail-recursive at first but it is a non-tail-recursive function. If we observe closely, we can see that the value returned by Recur_facto(n-1) is used in Recur_facto(n), so the call to Recur_facto(n-1) is not the last thing done by Recur_facto(n). 

    Python3

    Ví dụ 2: Factorial của 6 được ký hiệu là 6! = 1*2*3*4*5*6 = 720. & nbsp;

    Fibonacci series:
    0
    1
    1
    2
    3
    5
    8
    13
    21
    34
    
    2
    The factorial of 3 is 6
    5
    The factorial of 3 is 6
    24
    The factorial of 3 is 6
    7
    The factorial of 3 is 6
    7
    Traceback (most recent call last):
      File "", line 3, in 
      File "", line 2, in a
      File "", line 2, in a
      File "", line 2, in a
      [Previous line repeated 996 more times]
    RecursionError: maximum recursion depth exceeded
    3
    The factorial of 3 is 6
    28

    The factorial of 3 is 6
    2
    Fibonacci series:
    0
    1
    1
    2
    3
    5
    8
    13
    21
    34
    
    6

    The factorial of 3 is 6
    4
    The factorial of 3 is 6
    5
    Fibonacci series:
    0
    1
    1
    2
    3
    5
    8
    13
    21
    34
    
    9
    The factorial of 3 is 6
    7
    The factorial of 3 is 6
    7
    The factorial of 3 is 6
    8
    The factorial of 3 is 6
    9

    Traceback (most recent call last):
      File "", line 3, in 
      File "", line 2, in a
      File "", line 2, in a
      File "", line 2, in a
      [Previous line repeated 996 more times]
    RecursionError: maximum recursion depth exceeded
    6
    The factorial of 3 is 6
    41recurse0
    def recursor():
        recursor()
    recursor()
    6

    Chúng ta có thể viết hàm đã cho recur_facto dưới dạng hàm tái tạo đuôi. Ý tưởng là sử dụng thêm một đối số và trong đối số thứ hai, chúng tôi phù hợp với giá trị của giai thừa. Khi n đạt 0, trả về giá trị cuối cùng của giai thừa của số mong muốn. & Nbsp;

    Python3

    The factorial of 3 is 6
    2
    The factorial of 3 is 6
    45
    The factorial of 3 is 6
    7
    The factorial of 3 is 6
    8
    The factorial of 3 is 6
    28

    Fibonacci series:
    0
    1
    1
    2
    3
    5
    8
    13
    21
    34
    
    2
    The factorial of 3 is 6
    5
    The factorial of 3 is 6
    24
    The factorial of 3 is 6
    7
    The factorial of 3 is 6
    7
    Traceback (most recent call last):
      File "", line 3, in 
      File "", line 2, in a
      File "", line 2, in a
      File "", line 2, in a
      [Previous line repeated 996 more times]
    RecursionError: maximum recursion depth exceeded
    3
    The factorial of 3 is 6
    28

    The factorial of 3 is 6
    29
    factorial(3)          # 1st call with 3
    3 * factorial(2)      # 2nd call with 2
    3 * 2 * factorial(1)  # 3rd call with 1
    3 * 2 * 1             # return from 3rd call as number=1
    3 * 2                 # return from 2nd call
    6                     # return from 1st call
    1
    The factorial of 3 is 6
    58

    Fibonacci series:
    0
    1
    1
    2
    3
    5
    8
    13
    21
    34
    
    2
    factorial(3)          # 1st call with 3
    3 * factorial(2)      # 2nd call with 2
    3 * 2 * factorial(1)  # 3rd call with 1
    3 * 2 * 1             # return from 3rd call as number=1
    3 * 2                 # return from 2nd call
    6                     # return from 1st call
    1
    The factorial of 3 is 6
    61
    factorial(3)          # 1st call with 3
    3 * factorial(2)      # 2nd call with 2
    3 * 2 * factorial(1)  # 3rd call with 1
    3 * 2 * 1             # return from 3rd call as number=1
    3 * 2                 # return from 2nd call
    6                     # return from 1st call
    9
    The factorial of 3 is 6
    8
    The factorial of 3 is 6
    64
    Factorial of number 6 = 720
    
    3
    The factorial of 3 is 6
    66

    Traceback (most recent call last):
      File "", line 3, in 
      File "", line 2, in a
      File "", line 2, in a
      File "", line 2, in a
      [Previous line repeated 996 more times]
    RecursionError: maximum recursion depth exceeded
    6
    The factorial of 3 is 6
    41recurse0
    def recursor():
        recursor()
    recursor()
    6


    Làm thế nào để đệ quy hoạt động?

    Một hàm đệ quy giải quyết một vấn đề cụ thể bằng cách gọi một bản sao của chính nó và giải quyết các vấn đề nhỏ hơn của các vấn đề ban đầu.Nhiều cuộc gọi đệ quy hơn có thể được tạo ra khi được yêu cầu.Điều cần thiết là phải biết rằng chúng ta nên cung cấp một trường hợp nhất định để chấm dứt quá trình đệ quy này.. Many more recursive calls can be generated as and when required. It is essential to know that we should provide a certain case in order to terminate this recursion process.

    Hàm đệ quy với ví dụ trong Python là gì?

    Sau đây là một ví dụ về hàm đệ quy để tìm giai thừa của một số nguyên.Factorial của một số là sản phẩm của tất cả các số nguyên từ 1 đến số đó.Ví dụ: giai thừa của 6 (ký hiệu là 6!) Là 1*2*3*4*5*6 = 720.find the factorial of an integer. Factorial of a number is the product of all the integers from 1 to that number. For example, the factorial of 6 (denoted as 6!) is 1*2*3*4*5*6 = 720 .