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 QuestionFractals are one of my favorite things in math and computer science. They're fascinating because they combine simple patterns with infinite complexity, and they can be incredibly beautiful too! A fractal is a type of pattern that repeats itself on smaller and smaller scales. Imagine zooming in on a picture, and as you get closer, you see the same shape again and again, no matter how much you zoom. This property is called “self-similarity."
What’s truly exciting about fractals is that you can generate them using very simple rules and basic computer programs. For instance, one of the most famous fractals is the Mandelbrot set, which looks a bit like a warty bug and is created by repeating a simple mathematical operation. Despite the simplicity of the rules, the resulting images contain an endless depth of detail, with swirls and patterns emerging out of what started as just a few lines of code.
In computer science, fractals are a great example of how a straightforward algorithm can lead to outcomes that are unpredictably complex and often stunningly beautiful. They teach us about recursion, a concept where a function calls itself with a slightly altered input, which is a critical technique in programming. Moreover, they have practical applications too, such as in computer graphics for creating natural-looking scenery, in antenna theory for designing compact antennas, and even in medicine for analyzing patterns that occur in nature. So, diving into fractals not only expands your understanding of mathematics and programming but also opens up a world of applications that intersect with real-world problems and aesthetics.
One such mathematical pattern in computer science is the Mandelbrot Set. Here is a visualization of it:
Fractals are particularly interesting, because they also occur in nature. Check out my favorite: Romanesco Broccoli. I don’t know how it tastes, but it looks AMAZING.
You can produce fractals in Python, too. Try this code, which produces another famous fractal, the Dragon Curve:
If you look closely, you will see something interesting going on. Inside the main function called draw_dragon_curve( ), you will see calls to a function called draw_dragon_curve( ). Wait a minute. Yep - you read that right. This function calls itself to produce the fractal design. This is because fractals are a visual example of what we call “recursion” in Computer Science.
Recursion, simply put, is a function that calls itself.
Here is a much simpler example, that draws a simple fractal tree:
Play around with the code, and see what sort of interesting things you can produce. Can you make it bigger or smaller? Can you make different sized branches a different color or different line thickness? Can you put some leaves at the end of the smallest branches?