Recursion is a powerful programming technique where a function calls itself to solve a problem. However, it can lead to logical errors if not implemented correctly. Faulty recursion logic often results in infinite loops or stack overflows, making it crucial to understand common pitfalls. Below are three diverse examples that illustrate these issues and provide insights into debugging them.
In this example, a function is designed to calculate the factorial of a number using recursion. However, it fails to include a proper base case, leading to infinite recursion.
def factorial(n):
return n * factorial(n - 1)
result = factorial(5) # This will cause infinite recursion
The function factorial
is supposed to compute the factorial of a given number n
. However, it lacks a base case, which is essential to stop the recursion. Without a base case, the function continues to call itself indefinitely, resulting in a stack overflow error.
if n == 0: return 1
.In this example, a function attempts to reverse a string using recursion but mistakenly modifies the parameter, which leads to incorrect results.
```python
def reverse_string(s):
if len(s) == 0:
return s
return s[-1] + reverse_string(s[:-1]) # Correct logic
result = reverse_string(