0

I wrote the following function for Matrix transpose :

def transpose(mat):
    row = len(mat)
    column = len(mat[0])
    transposeMatrix = [[0] * row] * column  # Initialize Transpose Array
    for i in range(row):
        for j in range(column):
            transposeMatrix[j][i] = mat[i][j]
            print(f'output[{j}][{i}] = input[{i}][{j}] = {transposeMatrix[j][i]}')
    return transposeMatrix

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

The debugging print statement inside function seems to be working the way I wanted to, but the original output is always incorrect

Input: [[1,2,3],[4,5,6]]

Expected Output: [[1, 4], [2, 5], [3, 6]]

Original Output: [[3, 6], [3, 6], [3, 6]]

Alagusankar
  • 111
  • 1
  • 8
  • 1
    What output are you expecting and what do you get? I suspect your issue is due to https://stackoverflow.com/questions/12791501/python-initializing-a-list-of-lists – Guy Jun 07 '21 at 06:30
  • @Guy I updated the expected input and output. I don't think initialization is the problem here. When I tried to print the initialized array, it returned [[0, 0], [0, 0], [0, 0]] as I expected – Alagusankar Jun 07 '21 at 06:37
  • `transposeMatrix` creation is defiantly the issue, when I tried your code after fixing that part I got the expected output. – Guy Jun 07 '21 at 06:42
  • Also note that you can transpose a list-based matrix with a simple oneliner: `lambda a: [list(x) for x in zip(*a)]` – flawr Jun 07 '21 at 08:09

0 Answers0