CS 111
Spring 2018

Old version

This is the CS 111 site as it appeared on May 10, 2018.

Lab 7: Loops

Task 0: practice tracing loops

  1. Trace the following program using a table, and determine the output:

    values = [7, 2, 5, 3, 8]
    
    for i in range(len(values)):
        if values[i] % 2 == 1:
            values[i] = -1 * values[i]
    
    print(values)
    

    Here’s the beginning of the table:

    i values[i] action taken (if any)
    0 7 values[0] = -1*7 = -7
    ...

    Follow-up questions:

    • What is the output of this program?

    • Rewrite this program so that it uses a while loop instead of a for loop. The revised program should process the list in the same way as the original program. Here’s a template you can use:

      values = [7, 2, 5, 3, 8]
      
      i = 0
      while __________________:
          if values[i] % 2 == 1:
              values[i] = -1 * values[i]
          ______________________
      
      print(values)
      

At the end of the lab, you should turn in your paper trace to the TF. To get credit for attendance at today’s lab, you must have made a good effort on this trace.

Task 1: write functions that use a loop

Warning

When working with Python on the lab machines, make sure that you use a version of Python 3. Do not use a version of Python 2.

In IDLE, use the File -> New Window menu option to open a new editor window, and save it using the name lab7task1.py.

The manager of the Boston Bruins hockey team has asked us to write a program that will analyze the team’s results. These results will be represented by two lists of integers:

For example, here is one possible set of results:

bruins_goals = [1, 4, 3]
opponent_goals = [2, 1, 3]

Looking at these lists, we see that:

In this task, we’ll begin to implement some of the functionality that our program for the Bruins will need. We’ll do so by writing a series of functions, each of which uses a loop to process one or more lists of goals.

  1. Copy the following template into your file.

    def find_max_goals(goals):
        """ returns the largest number of goals in the specified 
            list of goals, which we assume contains at least one integer
        """
        maxg = goals[0]
    
        for g in goals:
            if ________________:
                ___________________
    
        return _____
    

    Replace the blanks with the code needed to create a function that takes a list of one or more integers containing the goals scored by a team, and that returns the maximum number of goals in that list. You may not use the built-in max() function.

    Hints:

    • The loop in our template is an element-based for loop. Given that fact, what values will the variable g take on?

    • You should use the variable maxg to keep track of the largest number of goals that you have seen thus far.

  2. Write a function find_num_wins(bruins, opponents) that takes two lists of integers containing the goals scored by the Bruins and their opponents (see above), and that returns the number of games that the Bruins won.

    For example:

    >>> find_num_wins([1, 4, 3], [2, 1, 3])        # won the second game 
    1
    >>> find_num_wins([1, 4, 3, 5], [2, 1, 3, 2])  # won second and fourth games
    2
    

    Hints:

    • This problem is best solved using an index-based for loop. Why?

    • This is a cumulative computation, so you will need to initialize an accumulator variable before the loop, and then increment the accumulator as needed within the body of the loop.

  3. Write a function print_results(bruins, opponents) that takes two lists of integers containing the goals scored by the Bruins and their opponents (see above), and that prints the results of each game in the format shown below. The function should not return a value.

    Here are two examples of what the format should look like:

    >>> print_results([1, 4, 3], [2, 1, 3])
    loss 1-2
     win 4-1
     tie 3-3
    >>> print_results([5, 3, 2, 1], [2, 1, 2, 4])
     win 5-2
     win 3-1
     tie 2-2
    loss 1-4
    

    Before you begin coding, ask yourself which type of for loop makes the most sense here: element-based or index-based?

    Hint: To print the score for a given game, you’ll need to:

    • use string concatenation so that there will be no spaces between the numbers and the hyphen (-)

    • use the str() function to turn each team’s number of goals into a string, so that you can then concatenate it.

Task 2: complete an interactive program

Although the functions from Task 1 are useful on their own, the Bruins want us to give them an interactive program so that they won’t need to remember how the functions work.

In lab7task2.py, we’ve given you some starter code for this interactive program. Download that file now and open it in IDLE.

Reviewing the starter code
The starter code includes several functions:

Let’s start by reviewing the main() method together. Among other things, we should answer the following questions:

Running the program
To run the program, you should:

At the moment, the only supported menu choices are 0 and 1, so go ahead and try executing each of those choices.

Adding support for choices 2-4
In Task 1, you already wrote the functions needed for choices 2-4.

To incorporate them into the program, you should:

A sample run that illustrates what the behavior of the program should look like is available here.

Adding support for new functionality
The Bruins would also like your program to be able to compute their complete record – i.e., their number of wins, losses, and ties.

This new functionality will be menu choice 5.

Write an appropriate separate function for choice 5. Your function should take whatever inputs is needs, and it should return the record as a list of the form [wins, losses, ties].

Once your function is working, add a new elif block for it in main(), and update the display_menu() function to add the choice to the menu.

Task 3: submit your work

You should turn in the paper with your work on Task 0 to the teaching fellow.

You should use Apollo to submit your lab7task1.py and lab7task2.py files.

Don’t worry if you didn’t finish all of the tasks. You should just submit whatever work you were able to complete during lab.

Here are the steps:

  1. Login to Apollo, using the link in the left-hand navigation bar. You will need to use your Kerberos user name and password.
  2. Check to see that your BU username is at the top of the Apollo page. If it isn’t, click the Log out button and login again.
  3. Find the appropriate lab section on the main page and click Upload files.
  4. For each file that you want to submit, find the matching upload section for the file. Make sure that you use the right section for each file. You may upload any number of files at a time.
  5. Click the Upload button at the bottom of the page.
  6. Review the upload results. If Apollo reports any issues, return to the upload page by clicking the link at the top of the results page, and try the upload again, per Apollo’s advice.
  7. Once all of your files have been successfully uploaded, return to the upload page by clicking the link at the top of the results page. The upload page will show you when you uploaded each file, and it will give you a way to view or download the uploaded file. Click on the link for each file so that you can ensure that you submitted the correct file.