Skip to content

Recursion

Also called: recursive, recursive function

Published:

How does recursion work?

NIST defines recursion as an algorithmic technique where a function, in order to accomplish a task, calls itself with some part of the task [1]. Every recursive solution has two parts. In the base case the problem is simple enough to solve directly. In the recursive case the function splits the problem into smaller pieces, calls itself on each and combines the results [1].

How do you sum 1 to n recursively?

This is one of NIST's own exercises [1]. Picture a function total(n): if n is 1, the answer is 1, which is the base case. Otherwise the answer is n + total(n - 1), the recursive case. Calling total(4) unfolds into 4 + total(3), the chain stops when it reaches total(1), and 4 + 3 + 2 + 1 = 10 comes back up.

Leave out the base case and the function calls itself forever. The same exercise list includes the classic companions: Fibonacci numbers, the greatest common divisor by Euclid's algorithm and exponentiation by repeated squaring [1].

Where does recursion hit its limits?

Every call takes room on the stack. Python therefore keeps a recursion limit, the maximum depth of the interpreter stack, so that infinite recursion cannot overflow the C stack and crash Python [2]. You can raise it with sys.setrecursionlimit(), but the documentation warns that a limit set too high can itself lead to a crash [2]. NIST lists iteration, divide and conquer and tail recursion as the related ideas worth knowing alongside it [1].

Frequently asked questions

Can a loop do what recursion does?

Usually, yes. The same problem can often be solved by iteration, which NIST lists as a related concept.

Why does Python raise RecursionError?

When the call depth exceeds the interpreter's recursion limit, or when the limit is set below the current depth.

Sources

  1. recursion — NIST Dictionary of Algorithms and Data Structures
  2. sys — System-specific parameters and functions — Python documentation