Hướng dẫn alternative to recursion python - thay thế cho python đệ quy

Tôi đang bắt đầu học Python. Ngay bây giờ tôi đang tạo CLI cho phép tạo, xem hoặc xóa các liên hệ được lưu trữ trong SQLite 3 dB. Vấn đề là mỗi khi tôi hoàn thành một tác vụ, tôi gọi lại chức năng chính để người dùng có thể làm những việc khác. Mã trông như thế này:

def main(self):
    print("What operation would you like to perform: Display contacts (1), add a new one (2), or remove one  (3)?")
    option = int(input())
    try:
        if option == 1:
            self.display()
            self.main()
        elif option == 2:
            self.new()
            self.main()
        elif option == 3:
            self.delete()
            self.main()
    except TypeError:
        print("Please introduce a valid option")
        sys.exit()

Tôi khá chắc chắn rằng các cuộc gọi liên tiếp của một hàm làm giảm hiệu suất của nó và tôi nghĩ rằng có giới hạn bao nhiêu lần bạn có thể gọi một hàm đệ quy, vậy tôi nên gọi lại phương thức chính như thế nào?

Hướng dẫn alternative to recursion python - thay thế cho python đệ quy

hỏi ngày 31 tháng 3 năm 2021 lúc 18:25Mar 31, 2021 at 18:25

Hướng dẫn alternative to recursion python - thay thế cho python đệ quy

2

Bạn đúng về các cuộc gọi đệ quy. Chúng có thể tốt, nhưng lặp lại thường tốt hơn đệ quy.

Có rất nhiều điều bạn có thể làm để thực hiện chương trình vô hạn, nhưng cách dễ nhất, đối với CLI, là đặt tất cả chức năng của bạn vào một vòng lặp.

Đây là loại xấu xí, nhưng điều đó sẽ hoạt động mà không cần bạn phải gọi Main () mọi lúc.

def main(self):
    again=True
    while again:
        print("What operation would you like to perform: Quit(0) Display contacts (1), add a new one (2), or remove one  (3)?")
        option = int(input())
        if option == 0:
            again=False
        if option == 1:
            self.display()
            self.main()
        elif option == 2:
            self.new()
            self.main()
        elif option == 3:
            self.delete()
            self.main()
        else:
            print("Please introduce a valid option")

Như đã nói, bạn vẫn phải gọi Main ()

Đã trả lời ngày 31 tháng 3 năm 2021 lúc 18:49Mar 31, 2021 at 18:49

VollfeiwvollfeiwVollfeiw

1751 Huy hiệu bạc9 Huy hiệu đồng1 silver badge9 bronze badges

3

Bạn có thể sử dụng các thư viện đối số như getopt hoặc argparse

Mục tiêu chính ở đây là quản lý các tùy chọn bên trong một vòng lặp và gọi tất cả cùng một lúc. Bán tại:

$ python3 ./script.py -123

Đã trả lời ngày 31 tháng 3 năm 2021 lúc 19:32Mar 31, 2021 at 19:32

Hướng dẫn alternative to recursion python - thay thế cho python đệ quy

Trong Python không có thứ gọi là "Hàm chính" hoặc "phương pháp chính". Nếu bạn muốn, bạn có thể đọc về các nhà xây dựng, hoạt động cuộc gọi, v.v. Vì vậy, nếu tôi hiểu chính xác - bạn muốn gọi lại phương thức "chính" cuộc gọi."main function" or "main method". If you want, you can read about constructors, call operations and etc. So, if I understood correctly - you want to recursive call "main" method.


Bạn có thể đếm các sự xuất hiện trong phương pháp này như thế này:

def main(self):
    again=True
    while again:
        print("What operation would you like to perform: Quit(0) Display contacts (1), add a new one (2), or remove one  (3)?")
        option = int(input())
        if option == 0:
            again=False
        if option == 1:
            self.display()
            self.main()
        elif option == 2:
            self.new()
            self.main()
        elif option == 3:
            self.delete()
            self.main()
        else:
            print("Please introduce a valid option")
3 và sau đó, nếu bạn muốn gọi đó là đệ quy, hãy tạo vòng lặp hoặc chỉ tổng hợp "đếm":


if count == :
    return
else:
    count += 5
self.main(count)

Đã trả lời ngày 31 tháng 3 năm 2021 lúc 18:44Mar 31, 2021 at 18:44

r1v3nr1v3nr1v3n

4053 Huy hiệu bạc9 Huy hiệu Đồng3 silver badges9 bronze badges

1

Bạn

def main(self):
    again=True
    while again:
        print("What operation would you like to perform: Quit(0) Display contacts (1), add a new one (2), or remove one  (3)?")
        option = int(input())
        if option == 0:
            again=False
        if option == 1:
            self.display()
            self.main()
        elif option == 2:
            self.new()
            self.main()
        elif option == 3:
            self.delete()
            self.main()
        else:
            print("Please introduce a valid option")
4 không trả lại bất cứ thứ gì bạn có thể viết theo cách nhỏ gọn hơn như sau:

Nội phân chính

  • Đệ quy là gì?
  • Chức năng đệ quy Python
  • Ví dụ về hàm đệ quy
  • Ưu điểm của đệ quy
  • Nhược điểm của đệ quy
  • Một lớp học có thể được đệ quy?
  • Làm thế nào để bạn gọi một chức năng đệ quy trong Python?
  • Hàm đệ quy trong ví dụ Python là gì?
  • Tôi có thể gọi một chức năng bên trong chính nó không?

def remove_text(input_str, to_remove):
    idx, len2 = input_str.find(to_remove), len(to_remove)
    if idx == -1:
        return input_str
    else:
        return remove_text(input_str[:max(0, idx - 1)] + input_str[idx + len2:], to_remove) 
        
result = remove_text("Hello my name is XXX Hello 12345 6 ", "Hello")

print(result)

Trong Python, một chức năng cũng có thể tự gọi! Một chức năng tự gọi được cho là đệ quy và kỹ thuật sử dụng một hàm đệ quy được gọi là đệ quy. Nó có vẻ kỳ dị cho một chức năng để tự gọi, nhưng nhiều loại vấn đề lập trình được thể hiện tốt nhất một cách đệ quy.

my name is XXX 12345 6 

Bạn

def main(self):
    again=True
    while again:
        print("What operation would you like to perform: Quit(0) Display contacts (1), add a new one (2), or remove one  (3)?")
        option = int(input())
        if option == 0:
            again=False
        if option == 1:
            self.display()
            self.main()
        elif option == 2:
            self.new()
            self.main()
        elif option == 3:
            self.delete()
            self.main()
        else:
            print("Please introduce a valid option")
4 không trả lại bất cứ thứ gì bạn có thể viết theo cách nhỏ gọn hơn như sau:

def remove_text(to_remove):
    global input_str
    idx, len2 = input_str.find(to_remove), len(to_remove)
    if idx > -1:
        input_str = input_str[:max(0, idx - 1)] + input_str[idx + len2: ]
        remove_text(to_remove)
    
input_str = "Hello my name is XXX Hello 12345 6 "
remove_text("Hello")
print(input_str)

Nội phân chínhbefore calling it.

Đệ quy là gì?

Nội phân chính

  • Đệ quy là gì?
  • Chức năng đệ quy Python
  • Ví dụ về hàm đệ quy
  • Ưu điểm của đệ quy
  • Nhược điểm của đệ quy
  • Một lớp học có thể được đệ quy?
  • Làm thế nào để bạn gọi một chức năng đệ quy trong Python?
  • Hàm đệ quy trong ví dụ Python là gì?
  • Tôi có thể gọi một chức năng bên trong chính nó không?
class mine:
    def inclass(self):
        self = mine();
    def recur(num):
        print(num, end="")
        if num > 1:
            print(" * ",end="")
            return num * self.recur(num-1)
        print(" =")
        return 1

def main():
    a = mine()
    print(mine.recur(10))

main()

Trong Python, một chức năng cũng có thể tự gọi! Một chức năng tự gọi được cho là đệ quy và kỹ thuật sử dụng một hàm đệ quy được gọi là đệ quy. Nó có vẻ kỳ dị cho một chức năng để tự gọi, nhưng nhiều loại vấn đề lập trình được thể hiện tốt nhất một cách đệ quy.


Bạn

def main(self):
    again=True
    while again:
        print("What operation would you like to perform: Quit(0) Display contacts (1), add a new one (2), or remove one  (3)?")
        option = int(input())
        if option == 0:
            again=False
        if option == 1:
            self.display()
            self.main()
        elif option == 2:
            self.new()
            self.main()
        elif option == 3:
            self.delete()
            self.main()
        else:
            print("Please introduce a valid option")
4 không trả lại bất cứ thứ gì bạn có thể viết theo cách nhỏ gọn hơn như sau:

class mine:
    def recur(self, num):
        print(num, end="")
        if num > 1:
            print(" * ",end="")
            return num * self.recur(self, num-1)
        print(" =")
        return 1

def main():
    a = mine()
    print(mine.recur(mine, 10))

main()

Nội phân chính

Đệ quy là gì?

Chức năng đệ quy Python

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


Chức năng đệ quy Python

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

Ưu điểm của đệ quy

Nhược điểm của đệ quy

Đầu ra

Ngay cả khi tôi không được đề xuất trong trường hợp cụ thể, bạn có thể đạt được kết quả tương tự mà không cần sử dụng

def main(self):
    again=True
    while again:
        print("What operation would you like to perform: Quit(0) Display contacts (1), add a new one (2), or remove one  (3)?")
        option = int(input())
        if option == 0:
            again=False
        if option == 1:
            self.display()
            self.main()
        elif option == 2:
            self.new()
            self.main()
        elif option == 3:
            self.delete()
            self.main()
        else:
            print("Please introduce a valid option")
5 chạy một cái gì đó như thế này:

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 điểm của đệ quy

The factorial of 3 is 6

Nhược điểm của đệ quy

Đầu ra

Ngay cả khi tôi không được đề xuất trong trường hợp cụ thể, bạn có thể đạt được kết quả tương tự mà không cần sử dụng

def main(self):
    again=True
    while again:
        print("What operation would you like to perform: Quit(0) Display contacts (1), add a new one (2), or remove one  (3)?")
        option = int(input())
        if option == 0:
            again=False
        if option == 1:
            self.display()
            self.main()
        elif option == 2:
            self.new()
            self.main()
        elif option == 3:
            self.delete()
            self.main()
        else:
            print("Please introduce a valid option")
5 chạy một cái gì đó như thế này:

def main(self):
    again=True
    while again:
        print("What operation would you like to perform: Quit(0) Display contacts (1), add a new one (2), or remove one  (3)?")
        option = int(input())
        if option == 0:
            again=False
        if option == 1:
            self.display()
            self.main()
        elif option == 2:
            self.new()
            self.main()
        elif option == 3:
            self.delete()
            self.main()
        else:
            print("Please introduce a valid option")
0

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

Đệ 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


if count == :
    return
else:
    count += 5
self.main(count)
1. Hãy nhìn vào một điều kiện như vậy.

def main(self):
    again=True
    while again:
        print("What operation would you like to perform: Quit(0) Display contacts (1), add a new one (2), or remove one  (3)?")
        option = int(input())
        if option == 0:
            again=False
        if option == 1:
            self.display()
            self.main()
        elif option == 2:
            self.new()
            self.main()
        elif option == 3:
            self.delete()
            self.main()
        else:
            print("Please introduce a valid option")
1

Đầu ra

def main(self):
    again=True
    while again:
        print("What operation would you like to perform: Quit(0) Display contacts (1), add a new one (2), or remove one  (3)?")
        option = int(input())
        if option == 0:
            again=False
        if option == 1:
            self.display()
            self.main()
        elif option == 2:
            self.new()
            self.main()
        elif option == 3:
            self.delete()
            self.main()
        else:
            print("Please introduce a valid option")
2

Ưu điểm của đệ quy

  1. Các chức năng đệ quy làm cho mã trông sạch sẽ và thanh lịch.
  2. Một nhiệm vụ phức tạp có thể được chia thành các vấn đề phụ đơn giản hơn bằng cách sử dụng đệ quy.
  3. Tạo trình tự dễ dàng hơn với đệ quy hơn là sử dụng một số lần lặp lồng nhau.

Nhược điểm của đệ quy

  1. Đôi khi logic đằng sau đệ quy là khó theo dõi.
  2. Các cuộc gọi đệ quy là tốn kém (không hiệu quả) vì chúng chiếm rất nhiều bộ nhớ và thời gian.
  3. Các chức năng đệ quy rất khó để gỡ lỗi.

Tham gia với chúng tôi và có quyền truy cập vào hàng ngàn hướng dẫn và một cộng đồng chuyên gia Pythonistas.

Mở khóa bài học này

Bài học này chỉ dành cho các thành viên. Tham gia với chúng tôi và có quyền truy cập vào hàng ngàn hướng dẫn và một cộng đồng chuyên gia Pythonistas.Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Mở khóa bài học này

Bài học này chỉ dành cho các thành viên. Tham gia với chúng tôi và có quyền truy cập vào hàng ngàn hướng dẫn và một cộng đồng chuyên gia Pythonistas. Looks like there’s an issue with video playback 🙁 This might be due to a temporary outage or because of a configuration issue with your browser. Please see our video player troubleshooting guide to resolve the issue.

  • Xin lỗi! Có vẻ như có một vấn đề với phát lại video 🙁 Điều này có thể là do sự cố ngừng hoạt động tạm thời hoặc do sự cố cấu hình với trình duyệt của bạn. Vui lòng xem Hướng dẫn khắc phục sự cố trình phát video của chúng tôi để giải quyết vấn đề.
  • Bảng điểm

Nhận xét & Thảo luận Using Recursion and a Python Class. Your first approach to generating the Fibonacci sequence will use a Python class and recursion. An advantage of using a class over the memoized recursive function you saw earlier is that a class keeps state and behavior together within the same object.

00:00 Sử dụng đệ quy và lớp Python. Cách tiếp cận đầu tiên của bạn để tạo chuỗi Fibonacci sẽ sử dụng lớp Python và đệ quy. Một lợi thế của việc sử dụng một lớp trên hàm đệ quy ghi nhớ mà bạn đã thấy trước đó là một lớp giữ trạng thái và hành vi cùng nhau trong cùng một đối tượng. This is known as encapsulation. In the function example,


if count == :
    return
else:
    count += 5
self.main(count)
2 is a completely separate object, so you don’t have control over it. On-screen, you can see the code that implements a class-based solution.

00:20 Điều này được gọi là đóng gói. Trong ví dụ chức năng,


if count == :
    return
else:
    count += 5
self.main(count)
2 là một đối tượng hoàn toàn riêng biệt, vì vậy bạn không có quyền kiểm soát nó. Trên màn hình, bạn có thể thấy mã thực hiện một giải pháp dựa trên lớp. Line 3 defines the

if count == :
    return
else:
    count += 5
self.main(count)
3 class. Line 4 defines the class initializer,

if count == :
    return
else:
    count += 5
self.main(count)
4. It’s a special method that you can use to initialize your class instances.

00:36 Dòng 3 Xác định lớp


if count == :
    return
else:
    count += 5
self.main(count)
3. Dòng 4 xác định trình khởi tạo lớp,

if count == :
    return
else:
    count += 5
self.main(count)
4. Nó có một phương pháp đặc biệt mà bạn có thể sử dụng để khởi tạo các phiên bản lớp của mình.
Special methods are sometimes referred to as dunder methods, short for double-underscore (

if count == :
    return
else:
    count += 5
self.main(count)
5) methods. Line 5 creates the

if count == :
    return
else:
    count += 5
self.main(count)
6 instance attribute, which means that whenever you create a

if count == :
    return
else:
    count += 5
self.main(count)
3 object, there will be a cache for it.

00:48 Các phương pháp đặc biệt đôi khi được gọi là các phương pháp Dunder, viết tắt cho các phương pháp kép (


if count == :
    return
else:
    count += 5
self.main(count)
5). Dòng 5 tạo thuộc tính thể hiện

if count == :
    return
else:
    count += 5
self.main(count)
6, có nghĩa là bất cứ khi nào bạn tạo đối tượng

if count == :
    return
else:
    count += 5
self.main(count)
3, sẽ có bộ đệm cho nó.
This attribute initially contains the first numbers in the Fibonacci sequence. Line 7 defines another special method,

if count == :
    return
else:
    count += 5
self.main(count)
8. This method turns the instances of Fibonacci into callable objects. Lines 9 to 12 validate the value of

if count == :
    return
else:
    count += 5
self.main(count)
9 by using a conditional statement.

01:02 Thuộc tính này ban đầu chứa các số đầu tiên trong chuỗi Fibonacci. Dòng 7 xác định một phương pháp đặc biệt khác,


if count == :
    return
else:
    count += 5
self.main(count)
8. Phương pháp này biến các trường hợp của Fibonacci thành các đối tượng có thể gọi được. Các dòng 9 đến 12 xác nhận giá trị của

if count == :
    return
else:
    count += 5
self.main(count)
9 bằng cách sử dụng một câu lệnh có điều kiện.
If

if count == :
    return
else:
    count += 5
self.main(count)
9 is not a positive integer, then the method raises a
def remove_text(input_str, to_remove):
    idx, len2 = input_str.find(to_remove), len(to_remove)
    if idx == -1:
        return input_str
    else:
        return remove_text(input_str[:max(0, idx - 1)] + input_str[idx + len2:], to_remove) 
        
result = remove_text("Hello my name is XXX Hello 12345 6 ", "Hello")

print(result)
1.

01:22 Nếu


if count == :
    return
else:
    count += 5
self.main(count)
9 không phải là một số nguyên dương, thì phương pháp này sẽ tăng
def remove_text(input_str, to_remove):
    idx, len2 = input_str.find(to_remove), len(to_remove)
    if idx == -1:
        return input_str
    else:
        return remove_text(input_str[:max(0, idx - 1)] + input_str[idx + len2:], to_remove) 
        
result = remove_text("Hello my name is XXX Hello 12345 6 ", "Hello")

print(result)
1.
Line 15 defines a conditional statement to check the Fibonacci numbers that were already calculated and are present in the cache. If the number index

if count == :
    return
else:
    count += 5
self.main(count)
9 is already in the cache, then line 16 returns it.

01:38 Dòng 15 Xác định một câu lệnh có điều kiện để kiểm tra các số Fibonacci đã được tính toán và có mặt trong bộ đệm. Nếu chỉ mục số


if count == :
    return
else:
    count += 5
self.main(count)
9 đã có trong bộ đệm, thì dòng 16 sẽ trả về nó. Otherwise, line 19 computes the number, and line 20 appends it to the cache so you don’t have to compute it again. Finally, line 22 returns the requested Fibonacci number.

01:53 Nếu không, dòng 19 tính toán số và dòng 20 nối nó vào bộ đệm để bạn không phải tính toán lại. Cuối cùng, dòng 22 trả về số Fibonacci được yêu cầu. To try this code, go ahead and save it into

def remove_text(input_str, to_remove):
    idx, len2 = input_str.find(to_remove), len(to_remove)
    if idx == -1:
        return input_str
    else:
        return remove_text(input_str[:max(0, idx - 1)] + input_str[idx + len2:], to_remove) 
        
result = remove_text("Hello my name is XXX Hello 12345 6 ", "Hello")

print(result)
3. Then run this code in your interactive shell in the same directory. Here you create and then call an instance of that

if count == :
    return
else:
    count += 5
self.main(count)
3 class named
def remove_text(input_str, to_remove):
    idx, len2 = input_str.find(to_remove), len(to_remove)
    if idx == -1:
        return input_str
    else:
        return remove_text(input_str[:max(0, idx - 1)] + input_str[idx + len2:], to_remove) 
        
result = remove_text("Hello my name is XXX Hello 12345 6 ", "Hello")

print(result)
5.

02:11 Để thử mã này, hãy tiếp tục và lưu nó vào

def remove_text(input_str, to_remove):
    idx, len2 = input_str.find(to_remove), len(to_remove)
    if idx == -1:
        return input_str
    else:
        return remove_text(input_str[:max(0, idx - 1)] + input_str[idx + len2:], to_remove) 
        
result = remove_text("Hello my name is XXX Hello 12345 6 ", "Hello")

print(result)
3. Sau đó chạy mã này trong vỏ tương tác của bạn trong cùng một thư mục. Tại đây bạn tạo và sau đó gọi một thể hiện của lớp

if count == :
    return
else:
    count += 5
self.main(count)
3 có tên
def remove_text(input_str, to_remove):
    idx, len2 = input_str.find(to_remove), len(to_remove)
    if idx == -1:
        return input_str
    else:
        return remove_text(input_str[:max(0, idx - 1)] + input_str[idx + len2:], to_remove) 
        
result = remove_text("Hello my name is XXX Hello 12345 6 ", "Hello")

print(result)
5.
The first call uses
def remove_text(input_str, to_remove):
    idx, len2 = input_str.find(to_remove), len(to_remove)
    if idx == -1:
        return input_str
    else:
        return remove_text(input_str[:max(0, idx - 1)] + input_str[idx + len2:], to_remove) 
        
result = remove_text("Hello my name is XXX Hello 12345 6 ", "Hello")

print(result)
6 as an argument and returns
def remove_text(input_str, to_remove):
    idx, len2 = input_str.find(to_remove), len(to_remove)
    if idx == -1:
        return input_str
    else:
        return remove_text(input_str[:max(0, idx - 1)] + input_str[idx + len2:], to_remove) 
        
result = remove_text("Hello my name is XXX Hello 12345 6 ", "Hello")

print(result)
6, which is the sixth Fibonacci number because you’re using zero-based indices.

02:32 Cuộc gọi đầu tiên sử dụng

def remove_text(input_str, to_remove):
    idx, len2 = input_str.find(to_remove), len(to_remove)
    if idx == -1:
        return input_str
    else:
        return remove_text(input_str[:max(0, idx - 1)] + input_str[idx + len2:], to_remove) 
        
result = remove_text("Hello my name is XXX Hello 12345 6 ", "Hello")

print(result)
6 làm đối số và trả về
def remove_text(input_str, to_remove):
    idx, len2 = input_str.find(to_remove), len(to_remove)
    if idx == -1:
        return input_str
    else:
        return remove_text(input_str[:max(0, idx - 1)] + input_str[idx + len2:], to_remove) 
        
result = remove_text("Hello my name is XXX Hello 12345 6 ", "Hello")

print(result)
6, đó là số Fibonacci thứ sáu vì bạn sử dụng các chỉ số dựa trên không.
This implementation of the Fibonacci sequence algorithm is quite efficient. Once you have an instance of the class, the

if count == :
    return
else:
    count += 5
self.main(count)
6 attribute holds the already-computed numbers from call to call.

02:48 Việc triển khai thuật toán trình tự Fibonacci này khá hiệu quả. Khi bạn có một thể hiện của lớp, thuộc tính


if count == :
    return
else:
    count += 5
self.main(count)
6 giữ các số đã được tính toán từ cuộc gọi đến cuộc gọi. In the next section of the course, you’ll take a deeper dive to visualize what happens when calling this recursive algorithm to get a better understanding of recursion and how memoization makes the algorithm more efficient.

03:00 Trong phần tiếp theo của khóa học, bạn sẽ đi sâu hơn để hình dung những gì xảy ra khi gọi thuật toán đệ quy này để hiểu rõ hơn về đệ quy và cách ghi nhớ làm cho thuật toán hiệu quả hơn.

Một lớp học có thể được đệ quy?.

Khi một đối tượng của một số lớp có giá trị thuộc tính của cùng một lớp, đó là một đối tượng đệ quy.

Làm thế nào để bạn gọi một chức năng đệ quy trong Python?tri_recursion() is a function that we have defined to call itself ("recurse"). We use the k variable as the data, which decrements (-1) every time we recurse. The recursion ends when the condition is not greater than 0 (i.e. when it is 0).

Trong ví dụ này, tri_Recursion () là một hàm mà chúng tôi đã xác định để tự gọi ("Recurse"). Chúng tôi sử dụng biến K làm dữ liệu, giảm (-1) mỗi khi chúng tôi tái diễn. Đệ quy kết thúc khi điều kiện không lớn hơn 0 (nghĩa là khi nó là 0).

Trong ví dụ trên, Factorial () 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.factorial() is a recursive function as it calls itself. When we call this function with a positive integer, it will recursively call itself by decreasing the number. Each function multiplies the number with the factorial of the number below it until it is equal to one.

Tôi có thể gọi một chức năng bên trong chính nó không?

Trong Python, một chức năng cũng có thể tự gọi!Một chức năng tự gọi được cho là đệ quy và kỹ thuật sử dụng một hàm đệ quy được gọi là đệ quy.Nó có vẻ kỳ dị cho một chức năng để tự gọi, nhưng nhiều loại vấn đề lập trình được thể hiện tốt nhất một cách đệ quy.it's also possible for a function to call itself! A function that calls itself is said to be recursive, and the technique of employing a recursive function is called recursion. It may seem peculiar for a function to call itself, but many types of programming problems are best expressed recursively.