15-112 Spring 2013 Quiz 6
* 25 Minutes. No calculators, no notes, no books, no computers.
* Show your work. Circle your answers.
1. Quick Answers. [10 pts]
a. What is the key difference between a list and a tuple?
b. Given a 2d list L, it is possible for a function to return an alias to any row in L, but it is impossible for the function to return an alias to any column in L. In just a few words, why is that impossible?
2. Code Tracing [15 pts] Indicate what this will print:
import copy
def f(L):
(L1, L2, L3) = (L, copy.copy(L), copy.deepcopy(L))
L1[0][0] = 7
L2[0][1] = 8
L3[1][0] = 9
return (L1, L2, L3)
L = [[1, 2], [3, 4]]
M = f(L)
print M
for LL in M: print (L is LL, L == LL),
3.
Reasoning Over Code [15 pts]
Find arguments for the following function that makes it return True.
def g(L):
(m,n) = (len(L), len(L[0]))
A = [ ]
for r in xrange(m):
for c in xrange(n):
A.append(L[r][c])
assert(sorted(A) == range(m*n))
return (L[m-2][n-2] == L[m-1][n-1] + 1)
4. Free
Response: hasColOfZeros [10 pts]: Write the function hasColOfZeros(L) that
takes a 2d list L and returns True if at least one column in L only contains
0’s, and False otherwise.
5. Free
Response: hasMoveFromCellInDirection [50 pts]: Write the function
hasMoveFromCellInDirection from the Othello case study as posted in the course
notes. Of course, we don’t expect you to have memorized this, but rather
you should be familiar with it and be able to quickly derive it here from
first principles. To refresh your memory:
hasMoveFromCellInDirection(board,
player, startRow, startCol, dir)
This function takes an Othello board, the current player, the starting row and
column of the move, and the direction of the move, and returns True if a move
can be made at that location by that player on that board in that direction, and
False otherwise. You may also recall that
dir is an int where 0 is up-left,
and the directions proceed left-to-right, then top-to-bottom, so 1 is straight
up, 2 is up-right, and so on, up until 7 which is down-right. We have provided
the first line for you:
def hasMoveFromCellInDirection(board,
player, startRow, startCol, dir):
6.
Bonus/Optional: [5 pts] Indicate what the following will
print:
def h(L):
try: return [L if (L[0][0] == len(L)) else 42] + h(L[1:])
except: return L
print h([[1,2,3],[2,3,4],[4,5,6]])