Click here to Skip to main content
15,907,687 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
A two dimensional matrix can be represented in Python row-wise, as a list of lists: each inner list represents one row of the matrix. For instance, the matrix

1 2 3
4 5 6
would be represented as [[1, 2, 3], [4, 5, 6]].

The transpose of a matrix makes each row into a column. For instance, the transpose of the matrix above is

1 4
2 5
3 6
Write a Python function transpose(m) that takes as input a two dimensional matrix using this row-wise representation and returns the transpose of the matrix using the same representation.

Here are some examples to show how your function should work. You may assume that the input to the function is always a non-empty matrix.

>>> transpose([[1,4,9]])
[[1], [4], [9]]

>>> transpose([[1,3,5],[2,4,6]])
[[1, 2], [3, 4], [5, 6]]

What I have tried:

import math
def transpose(m):
result=[[[m[j][i] for j in range (len(m))] for i in range (len(m[0]))]
for r in result:
print(r)
Posted
Updated 3-Sep-18 0:30am
Comments
PIEBALDconsult 3-Sep-18 0:24am    
What have you already learned in class?
Patrice T 3-Sep-18 0:58am    
What is the question ?

1 solution

result=[[m[j][i] for j in range (len(m))] for i in range (len(m[0]))]
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900