What is Recursion?
Recursion occurs when a function calls itself to solve smaller instances of a problem. It is often used to solve tasks that can be broken down into repetitive sub-tasks, such as factorial calculations or traversing hierarchical data structures.
Why Use Recursion?
Recursion simplifies tasks that involve repetitive sub-problems like calculating a factorial or counting residents in nested lists of barangays. It can replace complex loops with simpler function calls for some algorithms.
Syntax
Define a base case to stop recursion, and include a recursive call that moves toward this base case.
x
1
def recursive_function(parameters):
2
if base_condition:
3
return result
4
else:
5
return recursive_function(modified_parameters)
Example
1
1
# Function to calculate factorial of a number using recursion
2
def factorial(n):
3
if n == 1:
4
return 1
5
else:
6
return n * factorial(n - 1)
7
8
# Calculate factorial of 5, often used for barangay event permutations
9
print("Factorial of 5:", factorial(5)) # Output: 120