2
\$\begingroup\$

What is the transpose of a matrix:

In linear algebra, the transpose of a matrix is an operator which flips a matrix over its diagonal; that is, it switches the row and column indices of the matrix A by producing another matrix, often denoted by AT.

Code

dimension = int(input())
matrix = []
transpose = []
for row in range(dimension):
 entry = list(map(int,input().split()))
 matrix.append(entry)
for i in range(dimension):
 for j in range(dimension):
 transpose.append(matrix[j][i])
m = 0
n = dimension 
for x in range(dimension+1):
 
 row = transpose[m:n]
 list1 = [str(item) for item in row]
 string2 = " ".join(list1)
 print(string2)
 m = n
 n = n + dimension

My question

What all modifications I can do to this code to make it better furthermore efficient?

asked Oct 5, 2020 at 11:35
\$\endgroup\$
1
  • 1
    \$\begingroup\$ Example input and output would be useful. \$\endgroup\$ Commented Oct 5, 2020 at 22:01

2 Answers 2

5
\$\begingroup\$

You're converting the matrix elements to int and then back to string without doing anything with the ints, so that's just wasteful.

Anyway, the usual way to transpose is zip. Demo including mock input:

input = iter('''3
1 2 3
4 5 6
7 8 9'''.splitlines()).__next__
matrix = [input().split() for _ in range(int(input()))]
for column in zip(*matrix):
 print(*column)

Output:

1 4 7
2 5 8
3 6 9
answered Oct 5, 2020 at 22:12
\$\endgroup\$
3
\$\begingroup\$

You could do something like this:

dimension = int(input())
matrix = [list(map(int,input().split())) for _ in range(dimension)]
transpose = [[matrix[j][i] for j in range(dimension)] for i in range(dimension)]

PD: This still has to pass by every item on the matrix but it is a little more compact code, and if you're used to python you could find it a little more legible.

answered Oct 5, 2020 at 19:19
\$\endgroup\$
2
  • \$\begingroup\$ Other than code is more compact is there a performance improvement, does the code run faster? \$\endgroup\$ Commented Oct 5, 2020 at 20:15
  • \$\begingroup\$ Practically this code does less iterations, 2n^2 where n is the dimension (yours do 3n^2) But in terms of algorithmic complexity this is still O(n^2). \$\endgroup\$ Commented Oct 5, 2020 at 20:53

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.