Solutions to other tests:
Mathematics for the Digital Age
and
Programming in Python
>>> Second Edition
Test 14
- 1.
- C
- 2.
- (a) T (b) F (c) F
- 3.
- B
- 4.
- D
- 5.
- C
- 6.
- (b), (c)
- 7.
- (a), (b), (c)
- 8.
- (a) T (b) F (c) T (d) F
- 9.
- (a) T (b) T (c) F (d) T
- 10.
- D
|
- 11.
- B
- 12.
- C
- 13.
- A
- 14.
- (a), (b), (d), (f)
- 15.
- (a), (b), (d)
- 16.
- A
- 17.
- (a) T (b) T (c) T
- 18.
- D
- 19.
- (e), (f)
- 20.
- (a), (c)
|
- 21.
- def makeIdentity(n):
m = []
for i in range(n):
row = n * [0]
row[i] = 1
m.append(row)
return m
- 22.
- (a)
def sumRectangle(image, row1, col1, row2, col2):
return sum([sum(row[col1:col2]) for row in image[row1:row2]])
(b)
def findInk(image, size):
bestRow, bestCol = 0, 0
minSum = None
for r in range(0, len(image) - size + 1):
for c in range(0, len(image[0]) - size + 1):
s = sumRectangle(image, r, c, r + size, c + size)
if minSum is None or s < minSum:
minSum = s
bestRow, bestCol = r, c
return (bestRow, bestCol)
- 23.
- def isOrthogonal(m):
n = len(m)
for i in range(n):
if len(m[i]) != n:
return False
x = [row[i] for row in m]
if dotProduct(x, x) != 1:
return False
for j in range(i+1, n):
y = [row[j] for row in m]
if dotProduct(x, y) != 0:
return False
return True
There is a theorem that a matrix is orthogonal if and only if
the transposed matrix is orthogonal.
Therefore, we could use rows instead of columns of the matrix
for testing its orthogonality. The simplified code would be:
def isOrthogonal(m):
n = len(m)
for i in range(n):
if len(m[i]) != n:
return False
if dotProduct(m[i], m[i]) != 1:
return False
for j in range(i+1, n):
if dotProduct(m[i], m[j]) != 0:
return False
return True
- 24.
- (a)
def f(n):
_sum = 0
while n > 0:
d = n % 10
_sum += d ** 3
n //= 10
return _sum
(b)
def buildList(n, numbers):
lst = [n]
n = f(n)
while n not in lst and n in numbers:
lst.append(n)
n = f(n)
return lst
(c)
remainingNumbers = set(range(2000))
while len(remainingNumbers) > 0:
n = remainingNumbers.pop()
lst = buildList(n, remainingNumbers)
n = lst[-1]
n = f(n)
if n in lst:
print(lst[lst.index(n):])
remainingNumbers = remainingNumbers - set(lst)
- 25.
- def nChooseK(n, k, d = {}):
if k == 0 or k == n:
return 1
if (n, k) in d:
return d[(n, k)]
c = nChooseK(n-1, k-1) + nChooseK(n-1, k)
d[(n, k)] = c
return c
- 26.
- See ZipfsLaw.py.
|