## Exercises

Exercise 2.1. Make a Fahrenheit-Celsius conversion table.

Modify the c2f_table_while.py program so that it prints out a table with Fahrenheit degrees 0,10, 20,..., 100 in the first column and the corresponding Celsius degrees in the second column. Name of program file: c2f_table_while.py. O

### Exercise 2.2. Generate odd numbers.

Write a program that generates all odd numbers from 1 to n. Set n in the beginning of the program and use a while loop to compute the numbers. (Make sure that if n is an even number, the largest generated odd number is n-1.) Name of program file: odd.py. o

13 Any command you can run in the terminal window can also be run inside IPython if you start the command with an exclamation mark.

### Exercise 2.3. Store odd numbers in a list.

Modify the program from Exercise 2.2 to store the generated odd numbers in a list. Start with an empty list and use a while loop where you in each pass of the loop append a new element to the list. Finally, print the list elements to the screen. Name of program file: odd_list1.py. o

Exercise 2.4. Generate odd numbers by the range function.

Solve Exercise 2.3 by calling the range function to generate a list of odd numbers. Name of program file: odd_list2.py. o

Exercise 2.5. Simulate operations on lists by hand. You are given the following program:

a = [1, 3, 5, 7, 11] b = [13, 17] c = a + b print c d = [e+1 for e in a] print d d.append(b + 1) d.append(b[-1] + 1) print d

Go through each statement and explain what is printed by the program. o

Exercise 2.6. Make a table of values from formula (1.1).

Write a program that prints a table of t and y(t) values from the formula (1.1) to the screen. Use 11 uniformly spaced t values throughout the interval [0,2v0/g], and fix the value of v0. Name of program file: ball_table1.py. o

Exercise 2.7. Store values from formula (1.1) in lists.

In a program, make a list t with 6 t values 0.1, 0.2,..., 0.6. Compute a corresponding list y of y(t) values using formula (1.1). Write out a nicely formatted table of t and y values. Name of program file: ball_table2.py. o

### Exercise 2.8. Work with a list.

Set a variable primes to a list containing the numbers 1, 3, 5, 7, 11, and 13. Write out each list element in a for loop. Assign 17 to a variable p and add p to the end of the list. Print out the whole new list. Name of program file: primes.py. o

### Exercise 2.9. Generate equally spaced coordinates.

We want to generate x coordinates between 1 and 2 with spacing 0.01. The i-th coordinate, Xj, is then 1 + ih where h = 0.01 and i runs over integers 0,1,..., 100. Compute the xj values and store them in a list. Hint: Use a for loop, and append each new xj value to a list, which is empty initially. Name of program file: coorl.py. o

Exercise 2.10. Use a list comprehension to solve Exer. 2.9.

The problem is the same as in Exercise 2.9, but now we want the xi values to be stored in a list using a list comprehension construct (see Chapter 2.1.6). Name of program file: coor2.py. o

Exercise 2.11. Store data from Exer. 2.7 in a nested list.

After having computed the two lists of t and y values in the program from Exercise 2.7, store the two lists in a new list tl. Write out a table of t and y values by traversing the data in the tl list. Thereafter, make a list t2 which holds each row in the table of t and y values (tl is a list of table columns while t2 is a list of table rows, as explained in Chapter 2.1.7). Write out the table by traversing the t2 list. Name of program file: ball_table3.py. o

Exercise 2.12. Compute a mathematical sum.

The following code is supposed to compute the sum s = ^ ff=1 1:

s = 0; k = 1; M = 100 while k < M: s += 1/k print s

This program does not work correctly. What are the three errors? (If you try to run the program, nothing will happen on the screen. Type Ctrl-C, i.e., hold down the Control (Ctrl) key and then type the c key, to stop a program.) Write a correct program. Name of program file: compute_sum_while.py.

There are two basic ways to find errors in a program: (i) read the program carefully and think about the consequences of each statement, and (ii) print out intermediate results and compare with hand calculations. First, try method (i) and find as many errors as you can. Then, try method (ii) for M = 3 and compare the evolution of s with your own hand calculations. o

Exercise 2.13. Simulate a program by hand.

Consider the following program for computing with interest rates:

initial_amount = 100 p = 5.5 # interest rate amount = initial_amount years = 0

while amount <= 1.5*initial_amount: amount = amount + p/100*amount years = years + 1 print years

(a)Explain with words what type of mathematical problem that is solved by this program. Compare this computerized solution with the technique your high school math teacher would prefer.

(b)Use a pocket calculator (or use an interactive Python shell as substitute) and work through the program by hand. Write down the value of amount and years in each pass of the loop.

(c)Change the value of p to 5. Why will the loop now run forever? (See Exercise 2.12 for how to stop the program if you try to run it.) Make the program more robust against such errors.

(d)Make use of the operator += wherever possible in the program.

Insert the text for the answers to (a) and (b) in a multi-line string in the program file. Name of program file: interest_rate_loop.py. o

### Exercise 2.14. Use a for loop in Exer. 2.12.

Rewrite the corrected version of the program in Exercise 2.12 using a for loop over k values is used instead of a while loop. Name of program file: compute_sum_for.py. o

Exercise 2.15. Index a nested lists. We define the following nested list:

Index this list to extract 1) the letter a; 2) the list ['d', 'e', 'f']; 3) the last element h; 4) the d element. Explain why q[-1] [-2] has the value g. Name of program file: index_nested_list.py. o

Exercise 2.16. Construct a double for loop over a nested list.

Consider the list from Exercise 2.15. We can visit all elements of q using this nested for loop:

What type of objects are i and j? Name of program file: nested_list_iter.py. o

Exercise 2.17. Compute the area of an arbitrary triangle.

An arbitrary triangle can be described by the coordinates of its three vertices: (xi,yi), (x2,y2), (x3,y3). The area of the triangle is given by the formula

A = 1 [x2y3 - X3y2 - xiy3 + X3yi + xiy2 - X2yi] . (2.6)

Write a function area(vertices) that returns the area of a triangle whose vertices are specified by the argument vertices, which is a nested list of the vertex coordinates. For example, vertices can be [[0,0], [1,0], [0,2]] if the three corners of the triangle have coordinates (0, 0), (1, 0), and (0, 2). Test the area function on a triangle with known area. Name of program file: area_triangle. py. o

Exercise 2.18. Compute the length of a path.

Some object is moving along a path in the plane. At n points of time we have recorded the corresponding (x, y) positions of the object:

(x0,y0), (x^y2), • • -, (xra-1,yra-1). The total length L of the path from (x0,y0) to (xn-1,yn-1) is the sum of all the individual line segments ((xi-1 ,^¿-1) to (xi,y), i = 1, • • • - 1):

Make a function pathlength(x, y) for computing L according to the formula. The arguments x and y hold all the x0,...,xn-1 and yo,... ,yn-1 coordinates, respectively. Test the function on a triangular path with the four points (1,1), (2,1), (1, 2), and (1,1). Name of program file: pathlength.py. o

### Exercise 2.19. Approximate pi.

The value of n equals the circumference of a circle with radius 1/2. Suppose we approximate the circumference by a polygon through N+1 points on the circle. The length of this polygon can be found using the pathlength function from Exercise 2.18. Compute N + 1 points (xi, yi) along a circle with radius 1/2 according to the formulas xi = 1 cos(2ni/N), yi = 1 sin(2ni/N), i = 0,..., N .

Call the pathlength function and write out the error in the approximation of n for N = 2k, k = 2,3,..., 10. Name of program file: pi_approx.py. o

Exercise 2.20. Write a Fahrenheit-Celsius conversion table.

Given a temperature F in Fahrenheit degrees, the corresponding degrees in Celsius are found by solving (1.2) (on page 18) with respect to C, yielding formula (2.9). Many people use an approximate formula for quickly calculating the Celsius degrees: subtract 30 from the Fahrenheit degrees and divide by two, i.e.,

We want to produce a table that compares the exact formula (2.9) and the rough approximation (2.8) for Fahrenheit degrees between 0 and 100 (in steps of, e.g., 10). Write a program for storing the F values, the exact C values, and the approximate C values in a nested list. Print out a nicely formatted table by traversing the nested list with a for loop. Name of program file: f2c_shortcut_table.py. o

Exercise 2.21. Convert nested list comprehensions to nested standard loops.

Rewrite the generation of the nested list q, q = [r**2 for r in [10**i for i in range(5)]]

by using standard for loops instead of list comprehensions. Name of program file: listcomp2for.py. o

Exercise 2.22. Write a Fahrenheit-Celsius conversion function.

The formula for converting Fahrenheit degrees to Celsius reads