Recursion in Python? - with practical example

Recursion in Python is a powerful technique where a function calls itself in order to solve a problem. It is particularly useful when dealing with problems that can be broken down into smaller, similar subproblems. Example 1: Let's consider a classic example of recursion - calculating the factorial of a number. The factorial of a non-negative integer n is the product of all positive integers less than or equal to n. For example, the factorial of 5 is 5*4*3*2*1 = 120. 1. Define a recursive function called factorial that takes a single parameter n. 2. Check if n is equal to 0 or 1, return 1 in these cases as the factorial of 0 and 1 is 1. 3. If n is greater than 1, call the factorial function recursively with n-1 and multiply the result by n. 4. Repeat this process until n becomes 1, then return the final result.
def factorial(n):
    if n == 0 or n == 1:
        return 1
    else:
        return n * factorial(n - 1)

result = factorial(5)
print(result) # Output: 120

Example 2: Let's look at another example of recursion - calculating the Fibonacci sequence. The Fibonacci sequence is a series of numbers where each number is the sum of the two preceding ones. The sequence starts with 0 and 1. 1. Define a recursive function called fibonacci that takes a single parameter n. 2. Check if n is 0 or 1, return n in these cases as the Fibonacci of 0 and 1 is the number itself. 3. If n is greater than 1, call the fibonacci function recursively with n-1 and n-2, and return the sum of the results. 4. Repeat this process until n becomes 0 or 1, then return the final result.
def fibonacci(n):
    if n == 0 or n == 1:
        return n
    else:
        return fibonacci(n - 1) + fibonacci(n - 2)

result = fibonacci(6)
print(result) # Output: 8

Recursion is a powerful concept in programming that can simplify the solution to complex problems by breaking them down into smaller, more manageable subproblems. It is important to be cautious when using recursion as it can lead to stack overflow errors if not implemented carefully.

Comments

Popular posts from this blog

What are the different types of optimization algorithms used in deep learning?

Seven common machine learning evaluation metrics

Ten top resources for learning Python programming