Wondering if anyone could point me towards a good recursion tutorial. I am a bit rusty on it as I learned about it in my Data Structures class first semester. Would like to brush up on my recursion...any help?
I would highly recommend watching MIT's intro to programming course.
Lecture 4 talks about recursion.
Consider this.
More seriously…
Recursion is a way of solving problems that have a clearly defined base case (or cases, btu I'm keeping it simple here.)
For examples, the commonly cited factorial problem is a great one.
What does factorial do? Let's see some examples:
factorial(0) = 1
factorial(1) = 1
factorial(2) = 2
factorial(3) = 6
factorial(4) = 24
The factorial of a number is that number multiplied by the factorial of the number that comes before it, unless (now, this is the base case) the number is 0. The factorial of 0 is 1. (You can't take the factorial of a negative number; only positive integers.)
So we have our clearly defined base case. And we know what to do with numbers that aren't our base case (we multiply them times the factorial of the number one less than it.) We're ready to write our function.
def factorial(x):
if x == 0: # this is our base case
return 1 # and this is what we do when we see it
else: # this is what we do with all other numbers
return x * factorial(x-1)
So you
- Clearly define your base case.
- Find a way to reduce your problem from a non-base case to the base case.
Formally express that in a function that (when it's simple!) looks like
function: if base case: this else: something + function(something closer to the base case)
If you want something more advanced, Google's got a lot of info.