Recursion means functions calling themselves. Here is a quick guide to designing recursive functions:
Come up with a way to get the answer for more complicated/larger input by solving the problem for less complicated/smaller input.
To get the answer, you must know the answer to a less complicated question.
For example, to compute $n!$, we can first compute $(n-1)!$, and then multiply it by $n$, since $n! = 1\times 2\times 3\times 4...\times (n-1)\times n = (n-1)!\times n$.
Make sure that there is a a base case, i.e., that the recursion doesn't go on forever.
You can't push on a rope
For example, define $0! = 1$.
Let's now compute $n!$ using recursion:
def fact(n):
#Base case
if n == 0:
return 1
#Express the result in terms of the return value of fact(n-1)
return n*fact(n-1)
Here's what the locals tables will look like:
0
|
1
.
.
.
|
n-2
|
n-1
|
n
Once we reach the call to fact(0), we simply return. Note that if we didn't have the statement
if n == 0:
return 1
we would have infinite recursive calls (in theory; in practice, we'd just run out of memory), because we'd be trying to compute fact(-1), fact(-2), fact(-3), ... etc.