Lists and Loops

Before you begin PA #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
  • understand the purpose of functions and how to transform input into desired output

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 (1 hour or more): if you would like additional practice prior to starting the PA or would like additional practice in developing abstract thinking, we have provided an activity that provides a more interesting use case for the concepts from class. Doing this part will help you develop your computational thinking skills and will enable you to complete PA #1 more quickly.

Getting started

Open up a Linux terminal and navigate (cd) to your cmsc12100-aut-18-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 lab2 directory and run ipython3 in a Linux terminal.

It can be useful to know a few short cuts to manipulate your editor more effective, as it allows you to do more with fewer key strokes. Check out this link for sublime hot keys. Remember the old programmer adage: “a good programmer is a lazy programmer”.

Simple practice: Lists

Before you get started on this section, please run list_examples.py in ipython3:

In[4]: run list_examples.py

(The text In[x]:, where x is an integer, is the ipython3 prompt.)

This file contains a few lists (l0, l1, and l2) that you will use in the tasks for this section. You can see the value of a list just by typing its name in ipython3 (try doing this now to make sure you’ve loaded list_examples.py correctly):

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.

  1. [literals] Create a list that contains the values 7, “xyz”, and 2.7.
  2. [length] Compute the length of list l1.
  3. [indexing] Write expressions to retrieve the value 5.7 from list l1 and to retrieve the value 5 from the last element of l1.
  4. [indexing] Predict what will happen if you evaluate the expression l1[4] and then try it out.
  5. [indexing] Predict what happens if you evaluate the expression l2[-1] and then try it out.
  6. [indexing] Write a statement to change the value 3 inside the last element of l1 to 15.0.
  7. [slicing] Write an expression to create a slice containing the elements of index 1 through index 5 (inclusive) of list l2.
  8. [slicing] Write an expression to create a slice containing the first three elements of list l2.
  9. [slicing] Write an expression to create a slice containing the elements of index 1 through the last element (inclusive) of list l2.
  10. [operations] Write code to add four elements to list l0 using the append operation and then retrieve the element at index 3. How many appends do you need to do?
  11. [operations] Create a new list nl by concatenating the resulting value of l0 with l1 and then update an element of nl. Do either l0 or l1 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. The solutions to the tasks in this section have multiple lines, so you will want to put your code in a file (feel free to use list_examples.py for this purpose) and then run in ipython3. We recommend reviewing the Using an editor section of lab1 before you get started on this section.

Remember to save any changes that you make to the file and re-run it in ipython3.

  1. [basics] Write a loop to compute a variable all_pos that has the value True if all of the elements in the list l3 are positive and False otherwise.
  2. [loops & append] Write code to create a new list pos_only that contains only the positive values in the list l3.
  3. [loops & append] Write code that uses append to create a new list is_pos_0 in which the ith element of is_pos_0 has the value True if the ith element of l3 has a positive value and False otherwise
  4. [range, list initialization] Write code that uses range and list initialization to create a new list is_pos_1 in which the ith element of is_pos_1 is True if the ith element of l3 has a positive value and False otherwise. Hint: start by calculating a list of the right length with False at every index.
  5. [list initialization] Given a list l4 that contains values in the range from 0 to M inclusive, write code that determines M using the built-in max function and then creates a new list counts in which the ith element contains a count of the number of times the value i occurred in l4.

Part 2: Extended activity

Now that you have some practice with loops, we will move on to a more realistic example.

../../_images/integration_plot.svg

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

This code defines a new function (like print or math.cos) that takes a floating point value as an input and produces a floating point value as an output. In this sense it is a mathematical function like sin or log. 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.

\[\int_0^1 f(x) \,\mathrm{d}x = \int_0^1 x^2 \,\mathrm{d}x\]

We have defined a function integrate that you will use for this task. Add code to integrate to perform the following steps.

  1. Decide on a number of rectangles N (10 is a good number to start).
  2. Compute the width (dx) of your rectangles.
  3. Create a totalArea variable to store the sum of the areas of all the rectangles. Start it at zero.
  4. Make a loop with a variable, i that ranges from from 0 up to, but not including, N.
  5. 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 each i*dx and width is dx. Add this area to totalArea.
  6. After the for loop, return the value of totalArea using the statement: return totalArea.
  7. Celebrate; you have just replaced calculus.

Run integration_lab.py in ipython3 and then give your function a try by calling: integrate().

Errors

The value of this integral is

\[\int_0^1 x^2 \,\mathrm{d}x = \left[\frac{x^3}{3}\right]_0^1 = \frac{1^3}{3} - \frac{0}{3} = \frac{1}{3} = .33333333...\]

Did your code compute the correct value?

Try your program 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 quick lesson in abstraction

Changing the value of N in your function is tedious. Having multiple copies of your function for different values values of N is a very bad idea. To fix this problem, we can change the definition of integrate to take the number of rectangles as an argument named N instead. To see how this approach works, change the header for integrate to:

def integrate(N):

and then remove the line that initializes the value of N. Re-run integration_lab.py in ipython3 and then call integrate with different values for N (integrate(10) or integrate(10000), for example).

As you write code over the course of the term, you will want to look for these types of opportunities to exploit abstraction to create more general functions and reduce the amount of duplicated code in your programs.

Plotting functions

../../_images/example_plot.svg

In this section we will plot the sinc function, which is defined as follows:

\[\mathrm{sinc}(x) = \frac{\sin(x)}{x}\]

Open the file plot_lab.py and you will see that we have already defined this function for you under the name sinc.

This function is similar to f above, in that it is again a function in the mathematical sense, and we can draw it on a standard two dimensional plot as can be seen above.

Python has a very useful library named pylab that we can use to plot data. In particular, we’ll be using a function aptly named pylab.plot that can help us here. This function takes a list of floats with the x values and a list of floats with the y values as arguments, and produces an image of the corresponding x and y points plotted on a standard axis. (Note: either argument to pylab.plot can be an iterable, such as range, that yields floats instead of an explicit list.) We’ll also use the function pylab.show, which does not take any arguments, to display the plot.

In order to see what the sinc function looks like we will need to create lists of x and y values and then give these lists to the plot function.

Part A

In the function plot_sinc:

  1. Create and fill X with the values -10, -9, -8, ..., 9, 10 using the range function.
  2. Create an empty list Y.
  3. Use a for loop to fill the Y list with values equal to the sinc function called on each of the X values.
  4. Call pylab.plot with X and Y inputs and then call pylab.show() to show the plot.

Save your code, run plot_lab.py in ipython3, and then call plot_sinc() to see the plot.

Part B

The function is not clear from this image. The distance between points is too large. Instead of filling X with values -10, -9, ... make a list larger filled with values that are closer together like -10, -9.9, -9.8, -9.7, ..., -0.1, 0, 0.1, 0.2, 0.3, ..., 9.9, 10. The range function, which you used in Part A, generates integer values, but we’d like to use floating point values for the x values instead. Fortunately, there is an analogous library function numpy.arange for floating point values. It takes the same arguments as range (lower bound, upper bound, increment), but as floats rather than integers and it generates floats instead of integers. Change your code to:

  1. use numpy.arange instead of range in the computation of X and
  2. take the increment as an argument to plot_sinc rather than using a hard-coded value.

Then:

  1. Plot the function with spacing between x points equal to .1 by calling plot_sinc(.1).
  2. Plot the function with spacing between x points equal to .01 by calling plot_sinc(.01).

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 list_examples.py
git add integration_lab.py
git add plot_lab.py
git commit -m "Finished with lab2"
git push

No, we’re not grading your work. We just want to make sure your repository is in a clean state and that you have access to work your on both at CSIL and on your VM.