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.
- Check and see if there is more elephant.
- If there is more elephant, eat a spoonful of the elephant.
- Repeat.
Every recursive function has two parts
- Base Case This is a case that returns a value which ends the recursion.
- Recursive Step This returns a value that involves a call to the function. The argument passed in this call must bring the recursion closer to resolution.
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.
- What is the easiest set of items to do this on?
- Print an item, then print the rest (pachydermyphagy).
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!
$$$$$
$$$$
$$$
$$
$