Lab #1: Lists and Loops¶
Before you begin working on Programming Assignment #1, you should make sure you know how to:
do basic operations on lists
use for-loops to write repeated code
write code to construct new lists, append to existing lists, and index positions within a list
This lab will help you practice those skills. It has two main sections:
Part 1: Simple practice (30 minutes): the simple practice with lists and loops should be completed on a computer. This practice will help you gain familiarity with lists and loops, which are fundamental building blocks of writing code. This activity should take about 30 minutes to complete and will help prepare you to do PA #1.
Part 2: Extended activity (45 minutes or more): if you would like additional practice prior to starting the PA, we have provided a more complex exercise that provides a more interesting use case for the concepts from class.
Getting started¶
Open up a Linux terminal and navigate (cd) to your capp30121-aut-20-username
directory (where username
) is your CNetID. Run git pull upstream
master
to collect the lab materials and git pull
to sync with
your personal repository.
Once you have collected the lab materials, navigate to the lab1
directory and run ipython3
in a Linux terminal.
Simple practice: Lists¶
Before you get started on this section, copy-paste the following lines
into ipython3
:
l0 = []
l1 = [1, "abc", 5.7, [1, 3, 5]]
l2 = [10, 11, 12, 13, 14, 15, 16]
l3 = [7, -5, 6, 27, -3, 0, 14]
l4 = [0, 1, 1, 3, 2, 4, 6, 1, 7, 8]
These are the example lists we will use in this part of the lab.
Remember You can see the value of a list just by typing its name in
ipython3
(try doing this now to make sure you’ve created the lists):
In [5]: l0
Out[5]: []
In [6]: l1
Out[6]: [1, 'abc', 5.7, [1, 3, 5]]
In [7]: l2
Out[7]: [10, 11, 12, 13, 14, 15, 16]
Lists provide a way to represent ordered sequences of data. They are
an essential part of programming in Python and you will use them
repeatedly in your work. In this section, you will practice basic
list operations. Each task has one or more links to discussions of
the concepts needed to complete the task. Try doing the tasks in
ipython3
before you review the concepts.
[literals] Create a list that contains the values 7, “xyz”, and 2.7.
[length] Compute the length of list
l1
.[indexing] Write expressions to retrieve the value
5.7
from listl1
and to retrieve the value5
from the last element ofl1
.[indexing] Predict what will happen if you evaluate the expression
l1[4]
and then try it out.[indexing] Predict what happens if you evaluate the expression
l2[-1]
and then try it out.[indexing] Write a statement to change the value
3
inside the last element ofl1
to15.0
.[slicing] Write an expression to create a slice containing the elements of index 1 through index 5 (inclusive) of list
l2
.[slicing] Write an expression to create a slice containing the first three elements of list
l2
.[slicing] Write an expression to create a slice containing the elements of index 1 through the last element (inclusive) of list
l2
.[operations] Write code to add four elements to list
l0
using theappend
operation and then retrieve the element at index 3. How many appends do you need to do?[operations] Create a new list
nl
by concatenating the resulting value ofl0
withl1
and then update an element ofnl
. Do eitherl0
orl1
change as a result executing these statements?
Simple practice: Loops¶
Loops provide a mechanism for repeatedly performing a computation. They are often used in conjunction with lists in Python. As in the last section, this section contains a collection of tasks with links to discussions of the necessary concepts.
The list tasks were simple enough that you could easily type the
solutions into ipython3
directly. While you can continue to
use ipython3
to experiment with loops, you may also want to
put your your code in
a file (we have provided an empty loops.py
for this purpose) and
then run the file from the terminal:
$ python3 loops.py
We recommend reviewing the Using an editor section of lab0 before you get started on this section.
Remember to save any changes that you make to the file and re-run it in ipython3.
[basics] Write a loop to compute a variable
all_pos
that has the valueTrue
if all of the elements in the listl3
are positive andFalse
otherwise.[loops & append] Write code to create a new list
pos_only
that contains only the positive values in the listl3
.[loops & append] Write code that uses append to create a new list
is_pos_0
in which the ith element ofis_pos_0
has the valueTrue
if the ith element ofl3
has a positive value andFalse
otherwise[range, list initialization] Write code that uses range and list initialization to create a new list
is_pos_1
in which the ith element ofis_pos_1
isTrue
if the ith element ofl3
has a positive value andFalse
otherwise. Hint: start by calculating a list of the right length withFalse
at every index.[list initialization] Given a list
l4
that contains values in the range from0
toM
inclusive, write code that determinesM
using the built-inmax
function and then creates a new listcounts
in which the ith element contains a count of the number of times the value i occurred inl4
.
Part 2: Extended activity¶
Now that you have some practice with loops, we will move on to a more realistic example.
In this section we will compute definite integrals using numeric quadrature. The definite integral of a function is just the area under the curve of that function between two x values. We can calculate this area by filling in the curve with many small rectangles and then adding up the area of each of the rectangles - this method is aptly named the rectangle method.
In the file integration_lab.py
there is a function
def f(x):
return x*x
We have not covered functions in class yet, but don’t worry: all you need to know is that this function takes a number and produces the square of that number. Here are some sample uses of this function:
In [2]: f(3.0)
Out[2]: 9.0
In [3]: f(5.0)
Out[3]: 25.0
In this sense, it is a mathematical function like sin or log: it takes
a real number and produces another real number. More specifically, the function f
corresponds to the mathematical function \(f(x)
= x^2.\) We will use a for loop to compute the integral of this
function from 0 to 1 using N rectangles.
In the file integration.py
, we have provided the implementation
of the f
function, as well as an empty integrate
function where
you will write your code (similar to how you filled in a series of functions
in Short Exercises #1).
More specifically, you must add code to integrate
to perform the following steps:
Decide on a number of rectangles
N
(10 is a good number to start).Compute the width (
dx
) of your rectangles.Create a
total_area
variable to store the sum of the areas of all the rectangles. Start it at zero.Make a loop with a variable,
i
that ranges from from0
up to, but not including,N
.For each of these steps compute the area of the rectangle as height*width. Height is the value equal to the
f
function called on eachi*dx
and width isdx
. Add this area tototal_area
.After the for loop,
total_area
should contain the value of the integral.Celebrate; you have just replaced calculus.
Give the function a try from ipython3 (notice how, as in Short Exercises #1, we’re
using the autoreload feature; that way, ipython will reload the code in integration.py
automatically if you change that file):
$ ipython3
In [1]: %load_ext autoreload
In [2]: %autoreload 2
In [3]: import integration
In [4]: integration.integrate()
Out[4]: 0.33328333499999957
The value of this integral should be:
Did your code compute the correct value?
Try your function again but set the number of rectangles to 100 instead. Try 1000.
How many rectangles do you have to use to obtain a result that is correct enough?
A final note on functions¶
Of course, this function is pretty limited: it computes the integral of a specific function, between fixed bounds (0 and 1) and with a fixed set of rectangles. In Module M2: Functions, we will learn how we can add parameters to the function, so we can compute the integral of function ``f` with different bounds and rectangles.
When finished¶
When finished with the lab please check in your work. Assuming you are inside the lab directory, run the following commands from the Linux command-line:
git add loops.py
git add integration_lab.py
git commit -m "Finished with lab1"
git push
No, we’re not grading your work. We just want to make sure your repository is in a clean state and that your work is saved to your repository (and to our Git server)