Recursion In Python

Document
Image description

Recursion

Recursion involves a function calling itself directly or indirectly to solve a problem by breaking it down into simpler and more manageable parts.

Python Recursive Function

In Python, a recursive function is defined like any other function, but it includes a call to itself.

                
def factorial(n):
    if n == 1:
        return 1
    else:
        return n * factorial(n-1)

print(factorial(5)) 

                
            

Basic Structure of Recursive Fucntion

                
def recursive_function(parameters):


    if base_case_condition:


    return base_result


    else:


    return recursive_function(modified_parameters)
                
            

Advantages:

  • Easier to Understand: For some problems, like navigating through a tree-like structure, recursive solutions can be much easier to grasp and write compared to using loops.
  • Shorter Code: Often, you can express complex logic more concisely with recursion, leading to shorter and potentially more readable code.

Disadvantages:

  • Uses More Memory: Each time a function calls itself, it uses a bit of memory to keep track of where it was before. This can add up quickly, especially for deeply nested recursive calls.
  • Can be Slower: The overhead of making function calls can sometimes make recursive solutions run slower than equivalent solutions using loops.

Examples

Fibonnaci Series Using Recursion

        
def fibonacci(n):
if n <= 1:
    return n
else:
    return fibonacci(n-1) + fibonacci(n-2)
          
         
result = fibonacci(6)
print(f"6th Fibonacci number is: {result}")
        
    

Factorial Using Recursion

        
def factorial(n):

if n == 0:
    return 1
else:
    return n * factorial(n-1)

result = factorial(5) 
print(f"Factorial of 5 is: {result}")
        
    

Comments

Popular posts from this blog

Tkinter and Api

Sets in python