-1

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?

  • Stack Overflow is not an "explain why my code does this" website. Please take the [tour], read [ask] and [what's on-topic](/help/on-topic), and ask a _specific_ question about what you're confused about. Also useful: [How to debug small programs.](//ericlippert.com/2014/03/05/how-to-debug-small-programs/) | [What is a debugger and how can it help me diagnose problems?](//stackoverflow.com/q/25385173/843953) – Pranav Hosangadi Nov 05 '20 at 16:36

1 Answers1

-1

You can just use zip with map:

l=[[1,2,3],[4,5,6]]
print(list(map(list, zip(*l))))

And ahhh sweet, with numpy:

import numpy as np
l=[[1,2,3],[4,5,6]]
print(np.array(l).T.tolist())
Wasif
  • 14,755
  • 3
  • 14
  • 34