CS 111
Summer 2 2018

Problem Set 4 FAQ

Problem Set 4 FAQ

If you don’t see your question here, post it on Piazza or come to office hours! See the links in the navigation bar for both of those options.

You may also find it helpful to consult the general questions from the PS 3 FAQ, and the page we have assembled with info about common Python errors.

General questions

Questions on problem 1 (List comprehensions)

  1. I’m having trouble using range, how do I create a list of numbers with it?

    Recall that range(n) gives you a sequence of numbers from 0 to n-1. You can change the starting number by giving another parameter before n. For example, in order to get all the numbers from 2 to n-1, you could use range(2, n). It’s important that you do not put brackets around the call to range. Instead, you can use a call to range in conjunction with a list comprehension as in the following example:

    [x*2 for x in range(5)]

    If the length of the necessary list depends on the value of a variable, you can use the variable as the input to range. For example, let’s say that we want to write a function double(num_vals) that produces a list in which the integers from 0 to num_vals-1 are doubled. You could do something like this:

    def double(num_vals):
        """ docstring goes here
        return [2*x for x in range(num_vals)]

    Note that we use the parameter num_vals as the input to range.

  2. How do I use an if clause in my list comprehension for problem 1 part 3?

    You may find it helpful to look over the section entitled [List Comprehensions][pr4p1] in Chapter 3 of the CS for All textbook. They give an example that filters a list of strings based on the length of each string. In problem 2 part 3, we want you to filter the list based on whether each string ends with a suffix.

    Note that you should not make any assumptions about the length of suffix in your answer. You should use the len function to determine its length instead.