CS21 Lab 10: Recursion

Goals

The goals for this lab assignment are:

  • Practice tracing recursive functions

  • Designing recursive functions

  • Identifying base and recursive cases

1. Tracing: Stack Diagrams

The first part of this lab asks you to read three recursive functions. For each function, complete the following steps on paper.

  1. Identify the base case and recursive case.

  2. Trace the programs, and drawing the stack diagrams right up until the you reach the first return statement. Do not erase stack frames as you go along.

  3. Write down the final output of the program.

Please write your solutions on this document to make grading easier and more consistent. Upload your solution directly to Gradescope:

Example Question

Given the Python program shown below:

def fact(n):
    if n <= 1:
       return 1
    else:
       f = n * fact(n - 1)
       return f

def main():
   v = fact(4)
   print(v)

main()

Example Solution

  1. Base case: when n <= 1

  2. Recursive case(s): when n > 1

  3. The stack diagram would look like this if we stopped drawing just before the first return gets executed:

    example stack
  4. The final output of this program is:

    Output:
    24

2. Designing Recursive Functions

For this part of the lab, you will design and implement recursive functions.

When designing recursive programs, identify the base case(s) first: the simplest case where there is not a recursive call. Then move on to the recursive case(s).

Count letters

In the file count_letters.py write a recursive function called count_letters(txt, letter, index) that takes a string, txt, a single character letter, and an integer index, a as input parameters. The function should return a count of the number of times the letter appears in the string txt

Your solution must be recursive and cannot use the built in string method count.

When making your initial recursive call in, e.g., main, the first index must be len(txt)-1

def count_letters(txt, letter, index):
    """
    Recursively count the number of times letter appears in txt

    Parameters:
        txt (string): The string to inspect
        letter (string): A single character to search for in txt
        index (int): The current index to inspect in txt

    Returns:
        (int): A count of how many times letter appears in txt
    """

Examples:

# First example
word = "Mississippi"
idx = len(word)-1
count = count_letters(word, "s", idx)
print(count)  # prints 4

count = count_letters(word, "p", idx)
print(count)  # prints 2

count = count_letters(word, "q", idx)
print(count)  # prints 0

Make odd

In the file make_odd.py write a recursive function called make_odd(lst, index) that takes a list of integers, lst, and a index integer, and modifies the list to make each even number in the original list odd by adding 1 to the any even number.

You may assume the list will only contain non-negative integers and will not be empty.

When making your initial recursive call in, e.g., main, the first index must be len(txt)-1

Your solution must be recursive.

def make_odd(lst, index):
    """
    Recursively make any even numbers in lst odd by adding 1.

    Parameters:
        lst (list): A list of integers.
        index (int): The current index to inspect within the list.

    Returns:
        None. Modifies the list in place so each value is odd
    """

Examples:

# First example
ls = [4, 0, 6]
make_odd(ls, len(ls)-1)
print(ls) # prints [5, 1, 7]

# Second example
ls = [4, 1, 2, 9]
make_odd(ls, len(ls)-1)
print(ls) # prints [5, 1, 3, 9]

# Second example
ls = [9, 1, 9]
make_odd(ls, len(ls)-1)
print(ls) # prints [9, 1, 9]

Ruler

A typical ruler/tape measure has a series of marks of various lengths at regular intervals. For example, a ruler might have a long mark at every inch and a shorter mark at every half inch, and an even shorter mark every quarter inch. In the file ruler.py add a recursive function called ruler(n) that takes a non-negative integer n as its only parameter and prints an ASCII ruler according to the following rules:

  1. A ruler for n=0 has no marks.

  2. A ruler of n=1 has a single mark. You can print a single hyphen - to represent the mark.

  3. For a ruler of length n, it contains in sequential order the following elements:

    1. A smaller size n-1 ruler

    2. A mark of length n dashes

    3. A second smaller size n-1 ruler

For example, a ruler for n=2 would look like this:

-
--
-

A ruler for n=3 would look like this:

-
--
-
---
-
--
-

Can you identify the two n=2 ruler patterns in the n=3 ruler example? Your recursive function should not return anything. It should print the ruler directly to the screen.

def ruler(n):
    """
    This function recursively prints an ASCII ruler of size n

    Params:
        n(int): a non-negative integer


    Returns:
        None
    """

A ruler for n=5 would look like this:

-
--
-
---
-
--
-
----
-
--
-
---
-
--
-
-----
-
--
-
---
-
--
-
----
-
--
-
---
-
--
-
Your function might need to make two recursive calls.

Requirements

The code you submit for labs is expected to follow good style practices, and to meet one of the course standards, you’ll need to demonstrate good style on six or more of the lab assignments across the semester. To meet the good style expectations, you should:

  • Write a comment that describes the program as a whole using a comment at the top of the file.

  • All programs should have a main() function.

  • Use descriptive variable names.

  • Write code with readable line length, avoiding writing any lines of code that exceed 80 columns.

  • Add comments to explain complex code segments (as applicable).

  • Write a comment for each function (except main) that describes its purpose, parameters and return value.

In addition, you’ll need to demonstrate good top-down design practices on two or more lab assignments across the semester. To meet the top-down design expectations, you should:

  • Have a main() function that serves as an outline for your program.

  • Your main() function should call other functions that implement subtasks.

  • The functions that are called by main() should be well-named and have good comments explaining their purpose, parameters (including their types), and return value (including its type).

For EACH QUESTION in the stack-diagram portion of the lab, you should meet the following requirements:

  1. Draw the correct stack diagram.

  2. Show the base case and recursive case.

  3. Show the final output of the program.

For EACH PROGRAM in the function-writing portion of the lab, you should meet the following requirements:

  1. Your function should contain a non-recursive base case.

  2. Your function should make one or more recursive calls on a smaller version of the problem.

  3. Your function should correctly solve the problem.

  4. To test your solution, your main function should make at least three calls to the recursive function.

Answer the Questionnaire

After each lab, please complete the short Google Forms questionnaire. Please select the right lab number (Lab 10) from the dropdown menu on the first question.

Once you’re done with that, you should run handin21 again.

Submitting lab assignments

Remember to run handin21 to turn in your lab files! You may run handin21 as many times as you want. Each time it will turn in any new work. We recommend running handin21 after you complete each program or after you complete significant work on any one program.

Logging out

When you’re done working in the lab, you should log out of the computer you’re using.

First quit any applications you are running, including your vscode editor, the browser and the terminal. Then click on the logout icon (logout icon) and choose "log out".

If you plan to leave the lab for just a few minutes, you do not need to log out. It is, however, a good idea to lock your machine while you are gone. You can lock your screen by clicking on the lock xlock icon. PLEASE do not leave a session locked for a long period of time. Power may go out, someone might reboot the machine, etc. You don’t want to lose any work!