Computer Science

List comprehension

Use list comprehension to generate the list of all perfect numbers less than 10,000, $\{P_1,P_2,\ldots,P_N\}$.

What is their sum $\sum_i P_i$?

Assumptions and Details

• A perfect number is any integer which is equal to the sum of its proper divisors (all its divisors except for itself).

Suppose you're working on code for a molecular dynamics visualization. You need to represent various matrices, like the 3d rotation matrix, using Python lists. We can do so by using lists of lists.

For example, the matrix

$A= \begin{bmatrix} 1 & 0 & 0 \\ 0 & 1 & 0 \\ 0 & 0 & 1 \\ \end{bmatrix}$

is represented by

 1 A = [[1,0,0], [0,1,0], [0,0,1]] 

and the matrix

$B= \begin{bmatrix} 1 \\ 2 \\ 3 \\ \end{bmatrix}$

would be

 1 B = [[1],[2],[3]] 

The fragments below are designed to perform operations on matrices. Your task is to match the function bodies with the correct function definitions.

A:

 1 2 def getcolumn(matrix, i): # Given a matrix named 'matrix' this method should return the ith column 

B:

 1 2 3 def add(A, B): # Given two matrices (A and B) of the same dimensions, # this should return the sum of the two matrices 

C:

 1 2 3 def mult1D(row, col): # Given a row matrix[a1,a2..an] and a column[[r1],[r2]..[rn]] # matrix, this should return the 0D product [a1*r1 + a2*r2 .. an*rn] 

The function bodies are given by the following

1:

 1 2 [[A[j][i] + B[j][i] for i in range(len(A[0]))] for j in range(0, len(A))] 

2:

 1 [sum([row[i] * col[i][0] for i in range(len(row))])] 

3:

 1 [[r[i]] for r in matrix] 

In scientific computing, it is a common task to take the transpose of a matrix. The transpose of a matrix $A$, $A^T$, is found by turning all the rows of a matrix into columns and vice versa. More formally the transpose of a matrix $A$ is found by reflecting $A$ over its main diagonal.

For example, the transpose of

$A = \begin{bmatrix} 1 & 2 & 3 \\ 4 & 1 & 9 \\ 8 & 0 & 1 \\ \end{bmatrix}$

is given by

$A^T = \begin{bmatrix} 1 & 4 & 8 \\ 2 & 1 & 0 \\ 3 & 9 & 1 \\ \end{bmatrix}$

Which of the following snippets of code would correctly transpose the $30 \times 20$ matrix $A$?

A:

 1 2 transpose = [[a[i][j] for i in range(0, 30 + 1)] for j in range(0, 20 + 1)] 

B:

 1 2 transpose = [[a[i][j] for j in range(0, 30)] for i in range(0, 20)] 

C::

 1 2 transpose = [[a[j][i] for j in range(0, 30)] for i in range(0, 20)] 

D::

 1 2 transpose = [[a[i][j] for i in range(0, 30+1)] for j in range(0, 20+1)] 

×