Recursion
In questa pagina 9
Recursion is a programming paradigm: a function is recursivea function that calls itself while it is running when its body invokes the function itself. It looks impossible at first ("how can I call a function while it is running?"), but it is legal in Python as in almost all programming languages. Recursion is a powerful tool for building algorithms, but also the source of many hard-to-diagnose errors, so it must be understood precisely. Functions, loops and if statements are assumed from Programming FundamentalsThe CPU only executes machine instructions (opcodes) of its own instruction set; assembly languages give them mnemonic names and an assembler translates them one-to-one, but they are CPU specific; high-level languages are CPU independent and are translated by a compiler (executable code is CPU specific) or run by an interpreter; compiled languages are generally more efficient, interpreted languages more portable, and Java aims at both.Programming Fundamentals →. Its cost is studied in Computational ComplexityAlgorithms are analysed to predict performance on unseen inputs and to compare solutions of the same problem, mainly in time (also in space). Experimental analysis times an implementation (time.time(), doubling input sizes, T(n) = an^b with b = log2(T(2n)/T(n))) but measures the implementation, not the algorithm. Theoretical analysis counts basic steps under a cost model and classifies the result with asymptotic notation: O is an upper bound, Omega a lower bound, Theta both (f(n) <= cg(n) for all n >= n0). Rules: sum sequential blocks, take the larger branch of an if for an upper bound (the smaller for a lower bound), sum the iterations of a loop. Worked case: reverse a list with a shifting inner loop is Theta(n^2); writing each element directly in its place is Theta(n), and no faster hardware can compensate for the worse class on large inputs.Computational Complexity →.
1. A first example: the factorial
The factorial, widely used in combinatorics, is defined recursively: the function itself is used in its own definition.
The definition works. Developing it from :
- (by definition)
So for any positive integer the factorial is the product of the first positive integers:
Loop-based version (uses the product formula, i.e. the mathematical analysis done above):
# non-recursive factorial
def factorial(n):
result = 1
for i in range(1, n + 1):
result = result * i
return result
print(factorial(5)) # 120Recursive version (uses the definition directly, so it is more immediate to write; no analysis of the definition is needed):
# recursive factorial
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n - 1)
print(factorial(5)) # 1202. How a recursive call is executed
A recursive call is handled exactly like any other call:
- the execution of the invoking function is suspended;
- the invoked function runs until it terminates;
- the invoking function resumes from the point where it was suspended.
Sequence for :
factorial(3) invokes factorial(2)
factorial(2) invokes factorial(1)
factorial(1) invokes factorial(0)
factorial(0) returns 1
factorial(1) returns 1
factorial(2) returns 2
factorial(3) returns 6A list of pending calls is created, which grows and then shrinks until it dies out. Tracing the calls with print shows it:
def factorial(n):
print("entering factorial(" + str(n) + ")")
if n == 0:
print("base case: returning 1")
return 1
result = n * factorial(n - 1)
print("leaving factorial(" + str(n) + ") with " + str(result))
return result
print("Result:", factorial(3))entering factorial(3)
entering factorial(2)
entering factorial(1)
entering factorial(0)
base case: returning 1
leaving factorial(1) with 1
leaving factorial(2) with 2
leaving factorial(3) with 6
Result: 6All the "entering" lines come first (the list of pending calls grows), then the "leaving" lines in reverse order (it shrinks).
3. Rules for a correct recursive algorithm
To design a correct recursive algorithm two basic rules must be met.
1st rule: base case. The function must provide the solution in at least one particular case without using a recursive call. This case is the base casea case of the problem solved directly, without any recursive call. In the factorial it is:
if n == 0:
return 1There can be several base cases; it does not need to be unique.
2nd rule: recursive (or inductive) step. The function must make the recursive call after simplifying the problem. For the factorial of the function is called on , a simpler problem:
else:
return n * factorial(n - 1)What "simpler" means changes from problem to problem; in general the recursive calls must strive for a base case. In the mathematical definition, for is the base case and for is the recursive step.
Why the solution is an algorithm
These rules are what shows that a recursive solution is an algorithm, i.e. that it ends in a finite number of steps. Recursive calls might seem able to follow one another forever, but if
- with each recursive invocation the problem becomes simpler and simpler, and
- it approaches the base case, where the result does not require recursion,
then the solution is certainly computed in a finite number of steps (even a very high one), however complex the problem.
Never-ending recursion
Not all recursive functions implement correct algorithms. The recursion continues indefinitely if
- the base case is missing, or
- the problem is not simplified at each invocation.
def factorial(n):
if n == 0:
return 1
return n * factorial(n) # error: n does not decrease
print(factorial(3))RecursionError: maximum recursion depth exceededSince the list of pending calls grows without limit, the run-time environment runs out of memory to keep track of it and the program ends with an error. The simplest endless recursion is a function that only calls itself:
def endless_recursion():
endless_recursion()
endless_recursion() # RecursionError: maximum recursion depth exceededParameter errors
The mathematical definition holds for natural integers. With a negative argument the function never reaches the base case : it goes on with and the recursion never ends. Good practice is to check the input and raise an error:
def factorial(n):
if n < 0:
raise ValueError("n must be a natural number")
if n == 0:
return 1
return n * factorial(n - 1)
print(factorial(4)) # 24With a negative argument the function stops and the message n must be a natural number is shown on the terminal.
4. The call stack
When a function calls another one, the system must remember where to resume the execution once the called function finishes. It uses a structure called the call stackthe data structure inside the Python interpreter that keeps track of the pending (suspended) invocations:
- each call adds a new record to the stack;
- when the call ends, that record is removed;
- the stack keeps track of the suspended functions.
The bottom is the oldest call, the top the most recent one. For factorial(3) the stack holds, from the oldest to the most recent, factorial(3), factorial(2), factorial(1), factorial(0); the base case factorial(0) is the last one added, and it is the first to be removed.
Python sets a limit on the maximum stack depth, meant to prevent a recursive error from consuming memory uncontrollably. When the limit is exceeded a RecursionError is raised. The exact limit can be read with the sys module:
>>> import sys
>>> sys.getrecursionlimit()
10005. Types of recursion
5.1 Linear recursion
If a recursive function starts only one new recursive invocation at each execution, the recursion is linear. The factorial is linear: factorial(4) calls factorial(3), which calls factorial(2), ... down to factorial(0); the results 1, 1, 2, 6, 24 then come back up the chain.
5.2 Binary (double) recursion
When a function makes two recursive calls during its execution, the recursion is binary or double. Example: sum of the elements of a list from index low to index high, splitting the range in two halves.
# sums the elements of a list from index low to index high
def binary_sum(a, low, high):
if low > high: # base case 1: the dataset is empty
return 0
if low == high: # base case 2: the dataset contains a single element
return a[low]
mid = (low + high) // 2 # integer division
return binary_sum(a, low, mid) + binary_sum(a, mid + 1, high) # recursive stepThis function is clearly inefficient and only serves to illustrate binary recursion. It has two base cases (empty range, single element). The tree of the recursive calls for low = 0 and high = 7, written as (low, high):
(0,7)
(0,3) (4,7)
(0,1) (2,3) (4,5) (6,7)
(0,0)(1,1)(2,2)(3,3) (4,4)(5,5)(6,6)(7,7)Each range is split at mid; the leaves are the ranges with a single element.
5.3 Tail recursion
There is tail recursiona recursive function that performs a single recursive call and this call is the last action of the function:
def tail(...):
...
tail(...)The recursive factorial seen above is not, strictly speaking, tail recursive: the last statement executed is the multiplication n * factorial(n - 1), because after factorial(n - 1) returns we still have to multiply by n. A truly tail-recursive version uses an accumulatoran extra parameter that carries the partial result down the recursive calls, so that nothing is left to do after the call returns:
def factorial_tail(n, accumulator=1):
if n < 0:
raise ValueError("n must be a natural number")
if n == 0:
return accumulator
return factorial_tail(n - 1, accumulator * n)
print(factorial_tail(5)) # 120Eliminating tail recursion. A tail recursion can be transformed fairly easily into a loop: instead of opening a new call, the local variables are updated and the body of the function is repeated.
def factorial_iterative(n):
if n < 0:
raise ValueError("n must be a natural number")
accumulator = 1
while n > 0:
accumulator = accumulator * n
n = n - 1
return accumulator
print(factorial_iterative(5)) # 120Tail vs non-tail recursion, purpose and limits:
- tail recursion is not necessary, but in some cases it makes the code more readable; it is useful when the solution of the problem is explicitly recursive;
- in any case it is less efficient than the equivalent loop, because the system has to handle the suspended invocations;
- if the recursion is not in the tail it is not easy to eliminate it (to write equivalent non-recursive code), but it can be shown that this is always possible. It has to be so, because the processor executes instructions sequentially and cannot keep instructions waiting, so the interpreter takes care of eliminating the recursion (using the run-time stack).
5.4 Multiple recursion: Fibonacci numbers
We speak of multiple recursion when a function invokes itself several times during its execution. It is even more difficult to eliminate than tail recursion, but it is always possible. Example: the Fibonacci numbers.
| 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | |
|---|---|---|---|---|---|---|---|---|---|---|---|
| 0 | 1 | 1 | 2 | 3 | 5 | 8 | 13 | 21 | 34 | 55 |
The direct translation performs a binary recursion and is called fib_bad:
# returns the n-th fibonacci number
def fib_bad(n):
if n < 0:
raise ValueError("n must be non-negative")
if n < 2: # base cases
return n
return fib_bad(n - 2) + fib_bad(n - 1)Why it is bad. Multiple recursion must be used very carefully, because it can lead to very inefficient programs. Computing the Fibonacci numbers in ascending order, the processing time grows very rapidly: almost 3 million invocations are needed to calculate fib_bad(31). The reason is that multiple invocations with the same arguments are made. In the tree of fib(5):
fib(5)
fib(4) fib(3)
fib(3) fib(2) fib(2) fib(1)
fib(2) fib(1)fib_bad(1)is calculated 5 times,fib_bad(2)3 times,fib_bad(3)twice;- the tree grows very quickly: every non-base call generates two calls;
- the same value is recalculated many times.
The doubly recursive Fibonacci is useful for understanding multiple recursion, but it is not a good solution. The slides announce that the problem is quantified later (see Computational ComplexityAlgorithms are analysed to predict performance on unseen inputs and to compare solutions of the same problem, mainly in time (also in space). Experimental analysis times an implementation (time.time(), doubling input sizes, T(n) = an^b with b = log2(T(2n)/T(n))) but measures the implementation, not the algorithm. Theoretical analysis counts basic steps under a cost model and classifies the result with asymptotic notation: O is an upper bound, Omega a lower bound, Theta both (f(n) <= cg(n) for all n >= n0). Rules: sum sequential blocks, take the larger branch of an if for an upper bound (the smaller for a lower bound), sum the iterations of a loop. Worked case: reverse a list with a shifting inner loop is Theta(n^2); writing each element directly in its place is Theta(n), and no faster hardware can compensate for the worse class on large inputs.Computational Complexity → for the tools).
6. Thinking recursively: reversing a string
Goal: reverse a string with a recursive algorithm ("One" becomes "enO").
- Base case: if the string
shas fewer than 2 characters it is returned as it is, there is nothing to reverse. - Recursive step: take the first character
s[0], recursively reverse the substring with indexes from 1 tolen(s) - 1, and return the concatenation of the reversed substring followed by the first character. Example:s = "One"returns"en" + "O".
# Reverses the specified string
def reverse_string(s):
# base case
if len(s) < 2:
return s
# recursive step
r = reverse_string(s[1:])
return r + s[0]The substring s[1:] is shorter by one character at each call, so the problem is simplified and tends to the base case.
7. Towers of Hanoi
The Towers of Hanoi is a mathematical game with three rods and a number of disks of different diameters that can slide onto any rod. At the start the disks are stacked on one rod in order of decreasing size (the smallest at the top, a conical shape). The objective is to move the entire stack to the last rod, obeying the rules:
- only one disk may be moved at a time;
- each move takes the upper disk from one of the stacks and places it on top of another stack or on an empty rod;
- no disk may be placed on top of a disk that is smaller than it.
Solution with 3 disks, towers numbered 1, 2, 3 (the disks are the small, the medium and the large one; the sequence has 7 moves):
| move | from | to |
|---|---|---|
| 1 | tower 1 | tower 3 |
| 2 | tower 1 | tower 2 |
| 3 | tower 3 | tower 2 |
| 4 | tower 1 | tower 3 |
| 5 | tower 2 | tower 1 |
| 6 | tower 2 | tower 3 |
| 7 | tower 1 | tower 3 |
Recursive algorithm. The general problem is moving disks from one tower to another, using the third as temporary storage. To move disks we suppose to be able to move disks, as always done in recursion. To move disks from tower 1 to tower 3:
- the disks on top of tower 1 are moved to tower 2, using tower 3 as temporary storage (a recursive call; at its end tower 3 is empty again);
- the disk left on tower 1 is moved to tower 3;
- the disks on tower 2 are moved to tower 3, using tower 1 as temporary storage (a recursive call; at its end tower 1 is empty).
The base case is (in the code, size 0 does nothing), which uses only step 2, with no recursive call.
# Solves the Hanoi tower moving disks from from_tower to to_tower
# using temp_tower for temporary storage
def solve_hanoi(from_tower, to_tower, temp_tower, size):
if size > 0:
solve_hanoi(from_tower, temp_tower, to_tower, size - 1)
print("move from T" + str(from_tower) + " to T" + str(to_tower))
solve_hanoi(temp_tower, to_tower, from_tower, size - 1)
# Solves the Hanoi tower with n disks
def hanoi_solver(n):
solve_hanoi(1, 3, 2, n)Trace for , solve_hanoi(1, 3, 2, 2) (calls with size = 0 do nothing and are omitted):
solve_hanoi(1, 3, 2, 2)
solve_hanoi(1, 2, 3, 1)
move from T1 to T2
move from T1 to T3
solve_hanoi(2, 3, 1, 1)
move from T2 to T3Number of moves. With disks the algorithm needs
moves. The legend of the monks who move 64 disks (the world ends when they finish): moves, about . At one move per minute (about 525,000 moves a year) it takes more than 30 trillion years; a 1 GHz processor making one move per clock interval (one billion moves per second) takes 18 billion seconds, about 584 years.
8. When to use recursion
Recursion is particularly natural when the problem has a recursive structure: mathematical definitions such as the factorial, tree structures, folders containing other folders, divide-and-conquer algorithms such as mergesort and binary search. However it is not always the best choice:
- a recursive solution can be less efficient than an equivalent loop because each call requires managing the stack;
- in Python, a recursion that is too deep produces an error (
RecursionError).
Recursion is often elegant, not always efficient.
| recursion is useful when... | a loop is better when... |
|---|---|
| the problem is naturally defined in terms of similar subproblems | the problem is a simple linear repetition |
| the recursive code is clearer than the iterative version | the depth of the calls can become very large |
| working with tree structures or problem subdivisions | maximum efficiency is needed and recursion does not add clarity |
General scheme of a recursive solution: define the problem; if it is a base case, return the direct solution; otherwise transform it into one or more simpler subproblems, call the function recursively on them (a new, simpler problem each time) and combine the results.
Typical mistakes
- Missing base case, or a base case that is never reached (e.g.
factorial(n)called on a negative number): endless recursion, thenRecursionError. - Recursive call on the same problem (
factorial(n)instead offactorial(n - 1)). - Calling a recursive function "tail recursive" when work remains after the call (
n * factorial(n - 1)): an accumulator is needed. - Using the doubly recursive
fib_badfor large : the same sub-problems are recomputed (almost 3 million calls forfib_bad(31)).
Versione ripasso
Definition. A recursivea function that calls itself while it is running function calls itself in its body. It is correct only with:
- a base case: at least one case solved without a recursive call (
if n == 0: return 1); - a recursive step: a call on a simpler problem that approaches the base case.
If the base case is missing or the problem does not shrink: RecursionError: maximum recursion depth exceeded.
Factorial. ; for ; loop form .
def factorial(n):
if n == 0:
return 1
return n * factorial(n - 1)Call stack. A call suspends the caller, the callee runs to its end, then the caller resumes. Pending calls form a stack: each call adds a record, each return removes one. Python limit: 1000 (sys.getrecursionlimit()); exceeding it raises RecursionError. For : factorial(3) waits for factorial(2), down to factorial(0) returning 1; then 1, 2, 6 come back up.
Errors to avoid.
return n * factorial(n):nnever decreases, so the recursion never ends.- A negative argument never reaches
n == 0: check the input andraise ValueError(...).
Types.
- Linear: one recursive call per execution (factorial).
- Binary: two calls.
binary_sum(a, low, high)splits the list atmid = (low + high) // 2; base cases: empty range (low > high, returns 0) and one element (low == high). Inefficient, used to illustrate the idea. - Tail: the recursive call is the last action. The factorial above is not tail recursive, because it multiplies after the call returns. Fix: an accumulatoran extra parameter that carries the partial result down the recursive calls, so that nothing is left to do after the call returns (
factorial_tail(n, accumulator=1), returnsaccumulatoratn == 0). A tail recursion becomes a loop that updates the variables (while n > 0,accumulator = accumulator * n,n = n - 1); the loop is more efficient. - Multiple: several recursive calls. Fibonacci: , , . The naive
fib_badrecomputes the same values: almost 3 million invocations forfib_bad(31); in the tree offib(5),fib_bad(1)appears 5 times.
Other examples.
reverse_string(s): base caselen(s) < 2returnss; stepreverse_string(s[1:]) + s[0].- Towers of Hanoi: move disks to the spare tower, move the disk left on the source tower, move the disks onto the target. Base case: one disk. Number of moves ; 64 disks give moves, about 584 years at one billion moves per second.
def solve_hanoi(from_tower, to_tower, temp_tower, size):
if size > 0:
solve_hanoi(from_tower, temp_tower, to_tower, size - 1)
print("move from T" + str(from_tower) + " to T" + str(to_tower))
solve_hanoi(temp_tower, to_tower, from_tower, size - 1)When to use. Good for naturally recursive structures (trees, nested folders, mergesort, binary search). It can be less efficient than a loop, and too deep a recursion raises RecursionError: elegant, not always efficient.
Common mistakes: missing or unreachable base case; recursive call on the same argument; calling a non-tail recursion "tail recursive"; using fib_bad for large .