I have just started learning about recursion but I’m having a hard time understanding it. Please would you recommend any links or books that explain recursion in detail.
8
Start with a piece of paper that has the number 1 on it and the phrase “change the number by adding one”. Do what is written on the piece of paper.
That quote is our function:
count = 1
def function():
global count
count += 1
Modify the note (our function) to say: “change the number by adding one, then do what is written on the note”. Do what is literally on the piece of paper – change the number, then do what is written on the paper, which is to change the number and do what is on the paper, which is to change the number and do what is on the paper, …
Again, that quote is our function:
count = 1
def function():
global count
count += 1
function() # <- this is what makes this function recursive
# ie: "do what is written on the paper"
That’s infinite recursion. When you call the function, it does something, and then it calls itself.
Practical recursion says you need some sort of condition to tell you when to stop. To do that, change what’s on the note to read “Change the number by adding one. If the number is less than 100, then do what is written on the paper”. Again, that quote is our function:
count = 1
def function():
global count
count += 1
if (count < 100):
function()
Generally speaking, every proper recursive function needs some sort of terminal condition — a test that prevents the function from calling itself forever.
Write on a piece of paper “Change the number by adding one, then do what is written on this paper”. Put that piece of paper in your pocket as a reminder of what recursion is.
Note: the fact that the example increments a number is not at all related to recursion in general. It’s just a simple way to represent “doing some work”. A recursive function doesn’t necessarily have to increment or decrement a counter. All it needs is some way to determine when there is no more work to be done.
If you still don’t understand what recursion is, read this answer to the question “Having trouble understanding recursion”.
4