0

I meet a weird bug in Leetcode 867. Transpose Matrix.

The question is

Given a matrix A, return the transpose of A.

The transpose of a matrix is the matrix flipped over it's main diagonal, switching the row and column indices of the matrix.

Example 1:

Input: [[1,2,3],[4,5,6],[7,8,9]] Output: [[1,4,7],[2,5,8],[3,6,9]] Example 2:

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

The code gives the right out is

`res = [[None] * len(A) for _ in range(len(A[0]))]
#res = [[None] * len(A)] * len(A[0]) # why this doesn't work

for r, row in enumerate(A):
    for c, val in enumerate(row):
        res[c][r] = val

return res`

My solution is

`res = [[None] * len(A)] * len(A[0]) # why this doesn't work

for r, row in enumerate(A):
    for c, val in enumerate(row):
        res[c][r] = val

return res`

which gives the input and the output as Your input [[1,2,3],[4,5,6]] Output [[3,6],[3,6],[3,6]] Expected [[1,4],[2,5],[3,6]]

**The only difference between my solution and the right answer is **

`res = [[None] * len(A) for _ in range(len(A[0]))]
res = [[None] * len(A)] * len(A[0]) # why this doesn't work`

**Why the second line doesn't work? **

[[None] * len(A) for _ in range(len(A[0]))] == [[None] * len(A)] * len(A[0]) returns True

1 Answers1

0

This is because

res = [[None] * len(A) for _ in range(len(A[0]))]

creates a list containing len(A[0]) different lists, whereas

res = [[None] * len(A)] * len(A[0]) # why this doesn't work

creates a list containing len(A[0]) references to the same list, so that modifying a value in one of them modifies it in all of them.

See List of lists changes reflected across sublists unexpectedly among others ...

Tané Tachyon
  • 1,092
  • 8
  • 11