Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

use python3 #!/usr/bin/python3 \'\'\'CPSC 254 - Assignment 09\'\'\' from test im

ID: 3758823 • Letter: U

Question

use python3

#!/usr/bin/python3

'''CPSC 254 - Assignment 09'''

from test import test


def transpose(mat):
'''Given a matrix represented by a list of lists of numbers, return the
transpose of it. The transpose of a matrix is created by reflecting it
over its main diagnal, which runs from top-left to bottom-right, write
its rows as its columns and its columns as its rows.

For example:
mat = [[1, 2, 3],
[4, 5, 6]]
transpose(mat) = [[1, 4],
[2, 5],
[3, 6]]

YOU MUST USE LIST COMPREHENSION.

Keyword arguments:
mat -- a list of lists of numbers

Return: list of list of numbers
'''
# +++Add code here+++


def main():
'''Provides some tests for transpose function'''
print('transpose')
test(transpose([[1]]), [[1]])
test(transpose([[1, 2], [3, 4]]), [[1, 3], [2, 4]])
test(transpose([[1, 2, 3], [4, 5, 6]]), [[1, 4], [2, 5], [3, 6]])
test(transpose([[1, 4], [2, 5], [3, 6]]), [[1, 2, 3], [4, 5, 6]])


if __name__ == '__main__':
main()

Explanation / Answer

# Matrix to be transposed X = [[12, 7, 2, 4, 6], [4, 5, 7, 2, 4], [3, 8, 12, 7, 2], [6 ,7, 3, 8, 12]] # initialize the transposed matrix # initial A with zeros row = [0 for i in range(len(X))] transposed1 = [row] * (len(X[0])) # initial B with zeros transposed2 = [] for i in range(len(X[0])): transposed2.append([0] * len(X)) # Print the initial matrices print transposed1 print transposed2 # iterate through rows (i) and columns (j) for i in range(len(X)): for j in range(len(X[0])): transposed1[j][i] = X[i][j] print transposed