Writing a recursive function is easier if you always follow the same three steps. Do not try to follow all the calls in your head: trust that the recursive call already works and concentrate on a single level.
A three-step method
- Base case: what is the smallest case, answered without thinking? (
0, a one-digit number, an empty string, a one-character string…). - Reduce: how do I make the problem a little smaller? (
n - 1,n // 10,text[1:]…). - Combine: if I already have the answer to the smaller problem, what do I do to get the current one? (add, multiply, append a letter…).
With numbers
Power of 2: 2 ** n is 2 * 2 ** (n - 1), and 2 ** 0 is 1.
def power_of_2(n):
if n == 0:
return 1 # base case
return 2 * power_of_2(n - 1) # reduce and combine
print(power_of_2(5)) # 32
Calculate power recursively follows the same idea with any base. And Create a recursive function to multiply is solved by thinking that multiplying is adding repeatedly.
Another example reducing with integer division: the sum of the digits of a number.
def sum_digits(n):
if n < 10:
return n # base case: a single digit
return n % 10 + sum_digits(n // 10)
print(sum_digits(472)) # 13
With strings
Strings are reduced with slices: text[1:] is the text without its first character.
def length(text):
if text == "":
return 0 # base case: empty string
return 1 + length(text[1:])
def count(text, letter):
if text == "":
return 0
if text[0] == letter:
return 1 + count(text[1:], letter)
return count(text[1:], letter)
print(length("hello")) # 5
print(count("banana", "a")) # 3
For Reverse a string recursively think: the reverse of a text is the reverse of the rest of the text, with the first character placed at the end. For Check palindrome recursively, compare the first and last characters: if they are different, it is not a palindrome; if they match, the result depends on what is left in the middle. The base cases are the empty string and the one-character string.
With lists
def largest(numbers):
if len(numbers) == 1:
return numbers[0] # base case
return max(numbers[0], largest(numbers[1:])) # the first against the largest of the rest
print(largest([4, 9, 2])) # 9
When there are two calls: Fibonacci
Sometimes the problem breaks into two subproblems. In the Fibonacci series each term is the sum of the previous two, so the function calls itself twice:
def fibonacci(n):
if n <= 2:
return 1 # base cases
return fibonacci(n - 1) + fibonacci(n - 2)
print([fibonacci(i) for i in range(1, 9)]) # [1, 1, 2, 3, 5, 8, 13, 21]
It is the idea of Calculate Fibonacci series numbers. Here too there are two base cases (the first two terms).
Before running: three questions
- Does it have a base case and do I always reach it?
- Does each call work with a smaller problem?
- Does it return something on every path (
returnin the recursive case too)?