CS 124
Fall 2023

Problem Set 5 FAQ

Problem Set 5 FAQ

If you don’t see your question here, post it on Piazza or come to TA help 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.