Recursion, how it can be used and compares to an iterative approach.
2.2.1 Programming Techniques
Programming Techniques — Note 2 of 6
Candidates need to understand the principle of recursion and the key features of a recursive algorithm, such as a stopping condition. Candidates need to be able to read, trace and write recursive functions, and translate between recursive and iterative solutions. Candidates need to understand the benefits and drawbacks of recursive and iterative solutions.
A recursive subroutine calls itself, working on a smaller version of the problem each time until it reaches a base case. Many problems, such as tree traversal and divide and conquer algorithms, are naturally recursive.
A subroutine that calls itself.
def factorial_recursive(n):
if n <= 1: # base case
return 1
return n * factorial_recursive(n - 1) # recursive call
def factorial_iterative(n):
result = 1
for i in range(2, n + 1):
result = result * i
return result
print(factorial_recursive(4)) # 24: 4 * 3 * 2 * 1
print(factorial_iterative(4)) # 24