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)
-
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 ton
-1. You can change the starting number by giving another parameter beforen
. For example, in order to get all the numbers from 2 ton
-1, you could userange(2, n)
. It’s important that you do not put brackets around the call torange
. Instead, you can use a call torange
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 functiondouble(num_vals)
that produces a list in which the integers from 0 tonum_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 torange
.