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
Input: [[1,2,3],[4,5,6]]
Output: [[1,4],[2,5],[3,6]]
my code:
def transpose( A):
length = len(A)
width = len(A[0])
res = [[0] * length] * width
for i in range(length):
for j in range(width):
res[j][i] = A[i][j]
return res
transpose([[1,2,3],[4,5,6]])
my code's result :
[[3, 6], [3, 6], [3, 6]]
I track in the double loop, every time the res is updated, the value of a column is updated.
def transpose( A):
length = len(A)
width = len(A[0])
res = [[0] * length] * width
for i in range(length):
for j in range(width):
res[j][i] = A[i][j]
print(i,j,'->',j,i)
print(res)
return res
transpose([[1,2,3],[4,5,6]])
The output information is as follows:
0 0 -> 0 0
[[1, 0], [1, 0], [1, 0]]
0 1 -> 1 0
[[2, 0], [2, 0], [2, 0]]
0 2 -> 2 0
[[3, 0], [3, 0], [3, 0]]
1 0 -> 0 1
[[3, 4], [3, 4], [3, 4]]
1 1 -> 1 1
[[3, 5], [3, 5], [3, 5]]
1 2 -> 2 1
[[3, 6], [3, 6], [3, 6]]
But the following code gets the correct result:
def transpose( A):
length, width = len(A), len(A[0])
res = [[0] * length for _ in range(width)]
for r, row in enumerate(A):
for c, val in enumerate(row):
res[c][r] = val
return res
transpose([[1,2,3],[4,5,6]])
It's confusing!Is there any difference between the two ways of loop?
Is it caused by the underlying code optimization during compilation?