Notes on recursion
* Here is the 4-step recipe to writing recursive functions:
1. define the function header and write the doc string
- what parameters does the function take?
- what does (will) the function do / return?
2. define the recursive case
- pretend you had a working version of your function, but it only works on smaller
versions of your current problem, how could you write your function?
- the recursive problem should be getting "smaller", by some definition of smaller
- other ideas:
- sometimes define it in English first and then translate that into code
- often nice to think about it mathematically, using equals
3. define the base case
- recursive calls should be making the problem "smaller"
- what is the smallest (or simplest) problem
4. put it all together
- first, check the base case
- return something (or do something) for the base case
- if the base case isn't true
- calculate the problem using the recursive definition
- return the answer
* Recursion has a similar feel to "induction" in mathematics
- proof by induction in mathematics:
1. show something works the first time (base case)
2. assume that it works for this time
3. show it will work for the next time
4. therefore, it must work for all the times
* Example: write a recursive function to reverse a string
1. define the function header and write the doc string
def reverse(some_string):
"""return the reverse of some_string"""
2. define the recursive case
- pretend we have a function called reverse that we can use but only on smaller strings
- to reverse a string
- remove the first character
- reverse the remaining characters
- put that first character at the end
reverse(some_string) -> reverse(some_string[1:]) + some_string[0]
3. define the base case
- in each case the string is going to get shorter
- eventually, it will be an empty string. what is the reverse of the empty string?
- ""
- could also stop already if the length of the string is 1, and just return it
4. look at reverse function in recursion.py code
- check the base case first: if the length of the string is 0
- otherwise
- call reverse again on the shorter version of the string
- append on what is returned