24 February 2022

Chapter 1 Quiz It's up five minutes prior to the start of class.

A Little Recursion

How do you eat an elephant? You need a sharpened spoon. Here is the procedure.

picture of an elephant

  1. Check and see if there is more elephant.
  2. If there is more elephant, eat a spoonful of the elephant.
  3. Repeat.

Every recursive function has two parts

Recall our "mystery" function


import sys
sys.setrecursionlimit(1005)
def meat(x):
    if x == 0:
        return 1
    return x*meat(x - 1)
print(meat(1000))

The conditional logic


    if x == 0:
        return 1

is the base case. Notice that no call to meat is made in it and that the return value is immediately decidable (it's 1).

The return statement


    return x*meat(x - 1)

contains the recursive step. Note that the value it is called for x - 1 is closer to 0 than x. Each step makes progress toward resolution.

This is how recursion works. It does give us a means of doing something repeatedly, and it is a form of looping.

Some Things for You to Try


def print_items(x):
    """prec: x is a list or a tuple
postcondtion:  Each item of the list is printed on its own line."""
    pass
print_items(("a", "b", "c"))

If this is done correctly, this will happen.

$ python items.py
a
b
c

This should work on any list or tuple. In fact, it will work on a string (what happens?). Note that you can ring down the curtain on a functions action with a return statement.

Clues Be guided by these thoughts.


def count_down(n):
    """precondition: n is a integer, n > 0
postcondition:  prints a "countdown" from n to 0.  """
    pass
count_down(10)

Here is is in action with n = 10

python rocket.py
10
9
8
7
6
5
4
3
2
1
0
Blast off!

def sum_squares(n):
    """precondition: n is an integer, n >= 0
postcondition: returns 1 + 4 + 9 + 16 + ... n**2"""
    pass
python sums.py
385

def make_triangle(n, ch):
    """precondition  n > 0 is a integer
ch is a one-character string
postcondition:  returns a string that will print a triangle
of copies of ch with one copy in the first row, two in the second, etc
    """
print(make_triangle(5, "$"))

python triangle.py
$
$$
$$$
$$$$
$$$$$

Now copy your function and name the copy upside_down(n, ch). The call upside_down(5, "$") should produce this output. See if you can do this with a fairly small change in make_triangle. Note: there is more than one way to solve this problem!


$$$$$
$$$$
$$$
$$
$

Bad Use of Recursion