Search code examples
pythonpython-3.xmatrixtransposeconfusion-matrix

Confused about creating a result matrix for NxN matrix transposition in Python


NxN Matrix transposing gives wrong answers upon making "result" matrix = input matrix

Novice programmer here. I am trying to transpose a NxN matrix. Putting the code here to make the problem clear:

def flippingMatrix(matrix):
    result=[[0 for i in range(len(matrix))] for j in range(len(matrix))]
    for i in result:
        print(i)
    
    for i in range(len(matrix)):
        for j in range(len(matrix)):
            result[j][i]=matrix[i][j]
    
    for i in result:
        print(i)
            

# //Main Program//
n = int(input().strip())

matrix = []

for i in range(n):
    matrix.append(list(map(int, input().rstrip().split())))

result = flippingMatrix(matrix)

Now, if we run this program, we input 'N' which is no. of rows and columns. And in the next line, elements into the matrix. This is the input that I gave:

2

1 2

3 4

The output:

[0, 0]     //This is the result matrix that I made//
[0, 0]
[1, 3]     //The final result matrix//
[2, 4]

Coming to the problem: If, I assign the

"result=matrix" 

instead of

result=[[0 for i in range(len(matrix))] for j in range(len(matrix))]

I get the wrong answer. I am assuming that we need a result matrix as only a layout of NxN matrix. Then why does making the result same as input gives wrong answer? It is anyways going to be overwritten.

With the same input as earlier, I get the following output:

[1, 2]     //Initial result matrix which is the copied input matrix//
[3, 4]
[1, 2]     //The final result matrix//
[2, 4]

I apologize if the problem is a bit unclear, I tried my best. If anyone needs further explanation, comment on this post and I will try to explain my problem

EDIT: The new code that I am using after I was suggested an edit. The new code is as follows and I am facing the same problem

def flippingMatrix(matrix):
result=matrix
for i in result:
    print(i)

for i in range(len(matrix)):
    for j in range(len(matrix)):
        result[j][i]=matrix[i][j]

return result
        

# //Main Program//
n = int(input().strip())

matrix = []

for i in range(n):
    matrix.append(list(map(int, input().rstrip().split())))

result = flippingMatrix(matrix)
print(result)

Now the problem here might be because of the assignment statement result = matrix. But I don't think result matrix should be zero in order to be rewritten.


Solution

  • So I learned by talking in comments with @slothrop, Python doesn't take copying of lists inside of lists lightly. In order to make a copy, I have to use different commands like so that it actually makes an independent 2D array:

    b = copy.deepcopy(a)
    b = [item[:] for item in a]
    b = [item.copy() for item in a]
    b = [list(item) for item in a]
    b = [copy.copy(item) for item in a]
    b = []; b.extens[a]
    

    The link to such other question is here.