Lab 10
This lab contains some examples of the type of problems you may encounter on the final exam. The lab is divided into two parts: The first part contains questions on reading and understanding python code, the second part contains programming problems. Problems are presented in no particular order. Don’t assume that the first is easier than the second, and so on.
To check your answers to the exercises in the first part, compare with those of other students in the lab, and ask your tutor.
Exercise 1#
Each of the following pieces of python code attempt to compute and print
the maximum difference between any pair of numbers in a list x
. (Note
that the maximum difference is always greater than or equal to zero, which
is the difference between any number and itself.) For each one, you should
determine whether it is correct, meaning that it runs without error and
prints the correct value. If it is not, explain precisely what is wrong
with it.
Assume that variable x
is defined in the global namespace and that its
value is a non-empty list of numbers.
(a)
def find_max(x, y):
c = []
for i in x:
for j in y:
c.append(x[i] - y[j])
return max(c)
print("The max difference is ", find_max(x, x))
(b)
def find_max(x, y):
d = 0
for i in x and j in y:
d = max(d, i - j)
return d
print("The max difference is ", find_max(x, x))
(c)
def find_max(y):
z = x[0] * y
for i in range(len(x)):
x[i] = y * x[i]
if x[i] > z:
z = x[i]
return z
print("The max value is ", find_max(1))
print("The min value is ", find_max(-1))
print("The max difference is ", find_max(1) - find_max(-1))
(d)
def find max(x):
x = x.sort()
return x[-1] - x[1]
print("The max difference is ", find max(x))
Exercise 2#
Here is a function that takes as argument a sequence:
def funX(a_list):
index = 0
while index < len(sorted(a_list)) // 2:
index = index + 1
return sorted(a_list)[index]
(a) Explain what funX
does in general. A good answer is one
that describes the purpose of the function - something you would write
in its docstring.
(b) funX
is unnecessarily inefficient. Rewrite the function so
that it does the same thing, but as efficiently as possible.
Exercise 3#
Here is another function that takes a sequence as argument:
def funY(x):
i = 0
while i < len(x):
i = i + x[i] % len(x)
return i
(a) Give an example, if possible, of an argument sequence that
causes funY
to get stuck in an infinite loop, as well as an argument
sequence for which the function executes without error and returns a
value.
(b) What are the runtime errors that can occur in funY
, assuming
the argument is of type list
? For each error, give an example of an
argument list that causes the error.
Programming problems#
For each problem there is a problem description, a skeleton file for you to write your solution into, and a testing program (like the ones you have seen for the homework problems). Learn to use the testing program! It can provide useful feedback on errors in your solution, whether they are simple such as syntax errors or violations of the submission requirements, or semantic errors in your implementation.
Problem 1#
The integral of any function over a bounded interval [a,b] can be approximated by a sum. Each term in the sum approximates the integral over a small part of the interval with the area of a trapezoid that has two corners on the x-axis and two on the curve. For example, the following figure shows the curve x - x2 and two trapezoids: one over the interval [0.1, 0.4] and one over the interval [1.1, 1.4].
Let f(x) be the function that we want to integrate. The area of the trapezoid over the interval [x,x+d] is ((f(x) + f(x + d)) / 2) * d.
Write a function approximate_intergral(lower, upper, nterms)
that calculates an approximation of the integral of the function
f(x) = x3 (that is, x cubed) over a bounded interval
using the trapezoid method.
The three parameters of the function are the lower and upper bound
of the interval, and the number of terms in the sum. The function
should calculate the sum of nterms
trapezoids of equal width.
- You can assume that
lower
is less than or equal toupper
. - You can assume that
nterms
is a positive integer. - Your function should return a numeric value.
Example:
approximate_integral(0, 2, 2)
should return 5. The first trapezoid is over the interval [0,1] and has an area of 0.5 (((0 + 1) / 2) * 1); the second is over the interval [1,2] and has an area of 4.5 (((1 + 8) / 2) * 1).
You may recall that in Lab 4 you were asked to debug two incorrect solutions to this problem.
Files:
- Skeleton file: problem1.py
- Testing program: test_problem1.py
- Testing module: testing.py
Using the testing program:
To run the testing program, download both
test_problem1.py and its supporting
module testing.py and save them to the same
directory as your solution file. Then run test_problem1.py
.
The program will test the implementation of the function named
approximate_integral
in the file problem1.py
in the same directory.
If you have named your solution file differently, you need to change
the name of the tested file on the last line of the testing program.
Other than this, you should make no changes to the testing program.
Remember that:
- Your solution file must be syntactically correct python code.
- Your solution file must not contain anything other than function definitions, import statements and comments.
- You can use docstrings, but only inside a function definition.
The testing program will reject your file if it breaks any of these requirements.
Problem 2#
Let’s say that a counting dictionary is a dictionary
in which all values (not keys) are positive integers. (In other words,
it’s the kind of dictionary you get when you use a dictionary to count
repetitions of keys.) Given two count dictionaries, A
and B
, the
difference between A
and B
is another count dictionary that
contains the key-value pairs (k, n)
where n = A[k] - B[k]
for
exactly those keys k
such that n > 0
or k
appears only in A
.
Write a function count_dict_difference(A, B)
that takes as
arguments two count dictionaries and returns a new dictionary that
is the difference between them.
- You can assume that both arguments are dictionaries, and the values stored in them are integers.
- You should make no assumption about the types of keys that can appear in the dictionaries.
- Your function must not modify either of the argument dictionaries.
- Your function should value of type
dict
.
Example:
For example if A = {'s': 4, 'm': 1, 'p': 2, 'i': 4}
(that’s the
letter counts for the word ‘mississippi’) and
B = {'e': 1, 's': 3, 'm': 1, 'p': 1, 'i': 2, 't': 1}
(that’s the
letter counts for the word ‘pessimist’), the difference of A
and B
is the dictionary {'s' : 1, 'p' : 1, 'i' : 2}
(note how 'm'
is not
in the difference because A['m'] - B['m'] == 0
).
Files:
- Skeleton file: problem2.py
- Testing program: test_problem2.py
- Testing module: testing.py
Using the testing program:
To run the testing program, download both
test_problem2.py and its supporting
module testing.py and save them to the same
directory as your solution file. Then run test_problem2.py
.
The program will test the implementation of the function named
count_dict_difference
in the file problem2.py
in the same directory.
Remember that:
- Your solution file must be syntactically correct python code.
- Your solution file must not contain anything other than function definitions, import statements and comments.
- You can use docstrings, but only inside a function definition.
The testing program will reject your file if it breaks any of these requirements.
Problem 3#
The moving average of a numeric sequence is a sequence of averages
of subsequences of the original sequence; the subsequences are known
as windows (or a sliding window), and the length of the subsequence
used is called the window size.
More precisely, given a sequence S
, the moving average with window
size w
is sequence A
such that the first element in A
is the
average of w
consecutive elements in S
starting with the first,
the second element in A
is the average of w
consecutive elements
in S
starting with the second, and so on until the last element in
A
, which is the average of w
consecutive elements in S
ending
with the last.
Example:
If S = [2, 0, -2, 2]
and w = 2
, the moving average is [1, -1, 0]
.
1
is the average of [2, 0]
, -1
is the average of [0, -2]
, and
0
is the average of [-2, 2]
.
Write a function moving_average(seq, wsize)
that computes and returns
the moving average of seq
with window size wsize
.
- You should assume that the argument is a sequence of numbers (integer or floating point, or a mix of them).
- You can assume that
wsize
is an integer, at least 1, and less than or equal to the length ofseq
. - Your function must return a sequence of numbers (this can be, for example, a list, a tuple or NumPy array).
Files:
- Skeleton file: problem3.py
- Testing program: test_problem3.py
- Testing module: testing.py
Using the testing program:
To run the testing program, download both
test_problem3.py and its supporting
module testing.py and save them to the same
directory as your solution file. Then run test_problem3.py
.
The program will test the implementation of the function named
moving_average
in the file problem3.py
in the same directory.
Remember that:
- Your solution file must be syntactically correct python code.
- Your solution file must not contain anything other than function definitions, import statements and comments.
- You can use docstrings, but only inside a function definition.
The testing program will reject your file if it breaks any of these requirements.
Problem 4#
We say that a list that contains lists is nested. The result of unnesting (also known as “flattening”) a nested list is a list that contains the same non-list elements as the nested list, in the same order, but in a single list.
For example, [1, [2], [[3], [[4], 5]]]
is a nested list. The
unnesting of this list is [1, 2, 3, 4, 5]
.
Write a function called unnest
that takes as argument a list,
which may be nested, and returns the unnesting of the argument
list.
- You should assume that the argument is a list, and that all elements in the list are either lists or some non-sequence type.
- Your function must not modify the argument list. It must return
a value of type
list
.
Files:
- Skeleton file: problem4.py
- Testing program: test_problem4.py
- Testing module: testing.py
Using the testing program:
To run the testing program, download both
test_problem4.py and its supporting
module testing.py and save them to the same
directory as your solution file. Then run test_problem4.py
.
The program will test the implementation of the function named
unnest
in the file problem4.py
in the same directory.
Remember that:
- Your solution file must be syntactically correct python code.
- Your solution file must not contain anything other than function definitions, import statements and comments.
- You can use docstrings, but only inside a function definition.
The testing program will reject your file if it breaks any of these requirements.
Problem 5#
A closed interval of the real number line is defined by its lower
and upper end points.
Write a function interval_intersection(lA, uA, lB, uB)
that returns
the length of the intersection of two intervals A and B.
Arguments lA
and uA
are the lower and upper end points of interval
A, and lB
and uB
are the lower and upper end points of
interval B. If the intervals do not intersect, the function should
return 0.
For example, interval_intersection(0, 3, 1, 5)
should return
2
, because he intersection of the two intervals [0,3] and
[1,5] is [1,3], which has a length of 3 - 1 = 2.
- You can assume that the function’s arguments are numbers, but not that they are integers, or positive.
- Your function must return a number.
Files:
- Skeleton file: problem5.py
- Testing program: test_problem5.py
- Testing module: testing.py
Using the testing program:
To run the testing program, download both
test_problem5.py and its supporting module
testing.py and save them to the same directory
as your solution file. Then run test_problem5.py
. The program will
test the implementation of the function named interval_intersection
in the file problem5.py
in the same directory.
Remember that:
- Your solution file must be syntactically correct python code.
- Your solution file must not contain anything other than function definitions, import statements and comments.
- You can use docstrings, but only inside a function definition.
The testing program will reject your file if it breaks any of these requirements.