Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: In place transpose of a matrix

I tried writing an in-place transpose function just for practice. Can anyone tell me what's the time and space complexity for this algorithm?

from copy import *

def transpose(matrix):
    reference=deepcopy(matrix)
    col_num=len(reference[0])
    row_num=len(reference)
    matrix.clear()

    new=[list(map(lambda x: x[i],reference)) for i in range(col_num)]
    for i in new:
        matrix.append(new)
    return matrix

    x=[[ 1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]
    y=transpose(x)

Edit: Made my in-place transpose code more concise

like image 468
Prashin Jeevaganth Avatar asked Jan 17 '26 19:01

Prashin Jeevaganth


2 Answers

Option 1: If it's a square matrix NxN then:

def transpose(matrix):
    # Transpose O(N*N)
    size = len(matrix)
    for i in range(size):
        for j in range(i+1, size):
            matrix[j][i],matrix[i][j] = matrix[i][j],matrix[j][i]

Option 2: universal "pytonic" way is to do it like this:

mat = [[1,2,3],[4,5,6],[7,8,9]]
transpose = list(zip(*mat))
transpose
>>> [(1, 4, 7), (2, 5, 8), (3, 6, 9)]

zip function reference

like image 120
Gennadiy Ryabkin Avatar answered Jan 19 '26 18:01

Gennadiy Ryabkin


For the second loop, change to the following. In your code, you are going into an infinite loop.

    for row in matrix: 
        while len(row)!=row_num:
            if len(row)<row_num:
                row.append(0)
            else:
                row.pop()
like image 27
Christy Avatar answered Jan 19 '26 19:01

Christy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!