CS51A - Spring 2019 - Class 14

Example code in this lecture

   call_stack.py
   recursion.py

Lecture notes

  • administrative
       - Course feedback
       - Move Thursday office hours to 2:30-3:50pm
       - Lab is a required part of this course

  • the call stack
       - what is displayed if we call mystery(2, 3) in call_stack.py code?
          - The mystery number is: 15
       - why?

       - We can visualize each of these function calls:

       mystery(2, 3)
          |
          V
       "The mystery number is: " + c(2, 3)
                   |
                   V
                   b(6) - 1
                   |
                   V
                   6 + a()
                      |
                      V
                      10

       - Finally, when "a" returns it's value then we can work our way back and get the final answer
          - a() returns 10
          - which allows b to now return 16
          - once c knows it's call to b was 16, it returns 15
          - and finally, we can generate the string that the mystery function prints out
       
       - the way that the computer keeps track of all of this is called the "stack"
          - as functions are called, the stack grows
             - new function calls are added onto the stack
          - when functions finished, the stack shrinks
             - that function call is removed
             - its result is given to the next function on the stack (the function that called it)
       
       - you can actually see this stack (called the "call stack"), when you get an error, e.g. we change a to "return 10 + ''":

          - when we run it we see:

          >>> mystery(2,3)
          Traceback (most recent call last):
           Python Shell, prompt 2, line 1
           # Used internally for debug sandbox under external interpreter
           File "/Users/drk04747/classes/cs51a/examples/call_stack.py", line 11, in <module>
           print("The mystery number is: " + str(c(num1, num2)))
           File "/Users/drk04747/classes/cs51a/examples/call_stack.py", line 8, in <module>
           return b(num1 * num2) - 1
           File "/Users/drk04747/classes/cs51a/examples/call_stack.py", line 5, in <module>
           return num + a()
           File "/Users/drk04747/classes/cs51a/examples/call_stack.py", line 2, in <module>
           if __name__ == '__main__':
          builtins.TypeError: unsupported operand type(s) for +: 'int' and 'str'

          - it's a little bit cryptic, but if you look on the right, you see the call from mystery, to c, to b and finally to a

  • write a function called factorial that takes a single parameter and returns the factorial of that number
       >>> factorial(1)
       1
       >>> factorial(2)
       2
       >>> factorial(3)
       6
       >>> factorial(8)
       40320

       - look at factorial_iterative function in recursion.py
          - I'm guessing most people wrote it this way
          - does a loop from 2 up to n and multiplies the numbers
       - Another option is factorial_iterative2 in recursion.py
          - Here we did a range through n, so i goes from 0, 1, ..., n-1
          - In the body of the loop be multiply by i+1, i.e., by 1, 2, ..., n
       - could we have done it any other way?

  • recursion
       - a recursive function is defined with respect to itself
          - what does this mean?
             - somewhere inside the function, the function calls itself
             - just like any other function call
             - the recursive call should be on a "smaller" version of the problem
       - can we write factorial recursively?
          - key idea: try and break down the problem into some computation, plus a smaller subproblem that looks similar

             5! = 5 * 4 * 3 * 2 * 1
             5! = 5 * 4!

          - a first try:

             def factorial(n):
                return n * factorial(n-1)

          - what happens if we run this with say 5?
             5 * factorial(4)
                |
                V
                4 * factorial(3)
                   |
                   V
                   3 * factorial(2)
                      |
                      V
                      2 * factorial(1)
                         |
                         V
                         1 * factorial(0)
                            |
                            V
                            0 * factorial(-1)
                               ...

             - at some point we need to stop. this is called the "base case" for recursion
             - when is that?
                - when n = 1 (or if you want to account for 0!, at 0)
          - how can we change our function to do this?
       - look at factorial function in recursion.py code
          - first thing, check to see if we're at the base case (if n == 0)
             - if so, just return 1 (this lets 0! be 1)
          - otherwise, we fall into our recursive case:
             - n * factorial(n-1)   

  • writing recursive functions
       1. define what the function header is
          - what is the name of the function?
          - what parameters does the function take?
       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, e.g
                - for smaller numbers (like in factorial)
                - for lists that are smaller/shorter
                - for strings that are shorter
          - 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? This is often the base case
       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 some time
             3. show it will work for the next time (i.e. time after "some time")
             4. therefore, it must work for all the times

  • write a recursive function called rec_sum that takes a positive number as a parameter and calculates the sum of the numbers from 1 up to and including that number
       1. define what the function header is
          def rec_sum(n)

       2. define the recursive case
          - sum_{i=1}^n = 1+2+3+...+(n-1)+n = ???
             - can you rewrite this expression so that there's a sum on the right hand side (that's smaller?)
          - Another way to think about it: pretend like we have a function called rec_sum that we can use but only on smaller numbers
             rec_sum(n) = ?????? rec_sum(?)

          - rec_sum(n) = n + rec_sum(n-1)
             - i.e. the sum of the numbers 1 through n, is n plus the sum of the numbers 1 through n-1

       3. define the base case
          - in each case the number is getting smaller
          - what's the smallest number we would ever want to have the sum of?
             - 0
          - what's the answer when it's 0?
             - 0

       4. put it all together! - look at the rec_sum function in recursion.py code
          - check the base case first
             - if n == 0
          - otherwise
             - do exactly our recursive relationship