Introduction to Computer Science
CompSci 101 : Spring 2014

Understanding Code and Debugging

For the exercises below, first try using paper, pencil, discussion, and thinking (no computer) to solve them, before using the Python Interpreter to check your answers.

Read the SpeedDial problem statement to prepare for discussing several different solutions to the problem.

We will be working with the following example during this lab, so you should work it out by hand to remind yourself how the problem works:

numbers = [1111,123456,654321,1234567,7654321,123456789,111222,2222]
howMany = [3,4,5,8,7,2,2,3]
slots = 4 

Before looking at the given solutions, write two versions of a list comprehension that creates a list of the total number of key presses needed when there are no speed-dial slots. As a reminder, it will likely help to convert the integer values in the list numbers to string values using str, e.g., str(123) = "123" because you can use the len function with strings to easily determine the number of digits in each value.

  1. Use the Python function enumerate that returns a tuple of the index and the value of list at that index, like so for the list numbers:
    [(0,1111),(1,123456),(2,654321),(3,1234567),(4,7654321),(5,123456789),(6,111222),(7,2222)]

    With this list as the basis for your calculation in the list comprehension, you can use the index to access the two parallel lists, homMany and numbers.

    totalPressed = [                                                                     ]

  2. Use the Python function zip to combine the two parallel lists, numbers and homMany, into a single list of tuples of two items, the first from the list numbers and the second from the list homMany, like so:
    [(1111,3),(123456,4),(654321,5),(1234567,8),(7654321,7),(123456789,2),(111222,2),(2222,3)]

    This one list is what you will use as basis for your calculation in the list comprehension.

    totalPressed = [                                                                     ]

  3. Which function did you prefer to use to solve this specific problem and why?
  4. Now, consider these solutions to the SpeedDial problem. Each has a problem and does not work correctly for the example values on this page. For each solution, explain what the problem is and how to fix it in the context of that solution's code.