There are no problems that need to be solved by explicit recursion; and there are no problems that need to be solved using explicit iteration - the Church and Turing have proven that they are interchangeable.
However, there are problems that have cleaner code and are easier to reason with if you use recursion. In fact, the standard Python library and even the C code itself in many places use recursion internally and therefore tend to hit the extreme limit of recursion in many places, for example, print repr nested tuples:
>>> from functools import reduce >>> x = reduce(lambda x, y: (x,), range(10000)) >>> x # recursion limit hit in C code Traceback (most recent call last): File "<stdin>", line 1, in <module> RuntimeError: maximum recursion depth exceeded while getting the repr of a tuple >>> import pprint >>> pprint.pprint(x) # recursion limit hit in Python standard library code. Traceback (most recent call last): ... File "/usr/lib/python3.4/pprint.py", line 390, in _safe_repr orepr, oreadable, orecur = _safe_repr(o, context, maxlevels, level) File "/usr/lib/python3.4/pprint.py", line 340, in _safe_repr if issubclass(typ, dict) and r is dict.__repr__: RuntimeError: maximum recursion depth exceeded while calling a Python object
You can always convert a recursive algorithm into an iteration with a finite state machine and a stack of intermediate arguments, because after all this, what the CPU does to implement the recursion is pretty.
source share