Recursion is a programming technique in which a function calls itself to solve a problem. In other words, a function that calls itself is known as a recursive function, and the process of a function calling itself is called recursion. Recursion is a powerful concept used in various algorithms and problem-solving scenarios.
Let's start with a simple example of a recursive function to calculate the factorial of a positive integer.
def factorial(n):
if n == 0 or n == 1:
return 1
else:
return n * factorial(n - 1)
The factorial() function takes an integer n as input.
If n is 0 or 1, the function returns 1 as the factorial of 0 and 1 is 1.
Otherwise, the function returns the product of n and the result of calling factorial(n - 1), which calculates the factorial of the previous number.
print(factorial(5)) # Output: 120
print(factorial(0)) # Output: 1
print(factorial(1)) # Output: 1
The Fibonacci sequence is a series of numbers where each number is the sum of the two preceding ones. Let's create a recursive function to calculate the nth number in the Fibonacci sequence.
def fibonacci(n):
if n <= 0:
return "Invalid input. Please provide a positive integer."
elif n == 1:
return 0
elif n == 2:
return 1
else:
return fibonacci(n - 1) + fibonacci(n - 2)
print(fibonacci(7)) # Output: 8 (0, 1, 1, 2, 3, 5, 8)
print(fibonacci(10)) # Output: 34 (0, 1, 1, 2, 3, 5, 8,
Recursion is suitable for solving problems where a task can be divided into smaller subproblems, and each subproblem is similar to the original problem but smaller in size. Some use cases include:
Recursive functions can lead to excessive function calls, potentially causing a stack overflow if the recursion depth is too high. It is essential to have a base case that terminates the recursion.\
Recursion is an elegant approach for problems that have a natural recursive structure. It can lead to concise and readable code when the problem is well-suited for recursion. However, there are cases where recursion might not be the best choice:
In conclusion, recursion is a powerful concept in programming that allows solving complex problems by breaking them down into smaller subproblems. It is well-suited for problems with recursive structures, but it should be used judiciously, considering the problem's complexity, efficiency, and stack depth to avoid potential issues.
A very common use of recursion is the exploration of nested lists or linked items to explore them, count them, or catalog them. Below, I've provided an example of this. I've included comments in the code to explain each line, and below that I've provided a more readable explanation of the list structure and the traversal process.The list will be at least three levels deep, and each level will have strings starting with the letters 'A', 'B', 'C', etc.
We'll create a nested list with the following structure:
['A1', 'A2', ['B1', 'B2', ['C1', 'C2'], 'B3'], 'A3']
Here is a diagram that might make the structure a bit more clear:
The recursive function will start at the top level of the list and check each element:
def count_leaf_nodes(nested_list): # Initialize the count to 0 count = 0
# Iterate through each element in the nested list for element in nested_list: # If the element is a string, it is a leaf node, so increment the count if isinstance(element, str): count += 1
# If the element is a sublist (nested list), call the function recursively elif isinstance(element, list): count += count_leaf_nodes(element) # Return the total count of leaf nodes return count
# Nested list with strings at three levels deep nested_list = ['A1', 'A2', ['B1', 'B2', ['C1', 'C2'], 'B3'], 'A3'] # Call the recursive function to count leaf nodes result = count_leaf_nodes(nested_list) # Print the result print("Number of leaf nodes:", result) # Output: Number of leaf nodes: 6
Note: The recursive function traverses the nested list by exploring each level and counting the leaf nodes along the way. It continues to call itself recursively on sublists until all elements are checked, and the final count is returned.
No terms have been published for this module.
Test your knowledge of this module by choosing options below. You can keep trying until you get the right answer.
Skip to the Next Question