15-110 Fall 2010 Quiz 5
10 Minutes
* No calculators, no notes, no books, no computers.
* Show your work. Correct answers
without supporting calculations will not receive full credit.
1. Tracing
(30 pts)
Indicate what the following code will print.
A) (15 pts)
a = [ 1, 3, 2, 4]
x = 0
while (x < a[0]):
x += a.pop(0)
print x, a
B) (15 pts)
b = [ "a", "bcd", "ef" ]
d = [ ]
for x in b:
if (len(x) < len(b)):
for c in x:
d.append(c)
print d
2. Mystery
Method (20 pts)
State in just a few words of plain English what the following function does in
general:
def mystery(a, b):
# assume a and b are both lists of
integers
x = 0
for i in range(max(len(a), len(b))):
if (i < len(a)):
x += a[i]
if (i < len(b)):
x -= b[i]
return (x == 0)
3.
(50 pts) Write the function diagonal(matrix). This function takes a matrix (a rectangular
2d list), and if it is a square matrix (same number of rows as columns), the
function returns a 1d list composed of the values on the matrix’s top-left to
bottom-right diagonal. If the matrix is
not square, the function returns None.
For example:
diagonal([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
Returns:
[1, 5, 9]
4. Bonus/Optional (5 pts)
State in just a few words of plain English what the following function does in
general:
def mystery(a):
# assume a is a list of non-negative
integers
x = 0
for i in range(max(a)):
for z in a:
if (z > i):
x += z
return x