for i in range(n): for j in range(n): a, b = matrix[i][j], matrix[j][i] matrix[i][j] = b…
- User
for i in range(n): for j in range(n): a, b = matrix[i][j], matrix[j][i] matrix[i][j] = b matrix[j][i] = a why doesn't this swap position
- Assistant
The reason your code doesn't swap the elements correctly is that both loops run over all i and j — so each pair gets swapped twice, which effectively puts everything back where it started. Let’s walk through an example with a 2×2 matrix: pythonCopyEditmatrix = [ [1, 2], [3, 4] ]
Your code logic:
First swap: i=0, j=1
Swap (0,1) and (1,0) → matrix becomes csharpCopyEdit[1, 3] [2, 4]
Later: i=1, j=0
Swap (1,0) and (0,1) again → matrix goes back to csharpCopyEdit[1, 2] [3, 4]
The fix To avoid swapping twice, you should only iterate over half the matrix — for example, only when j > i: pythonCopyEditfor i in range(n): for j in range(i+1, n): # start from i+1 a, b = matrix[i][j], matrix[j][i] matrix[i][j] = b matrix[j][i] = a
This way, (i,j) is swapped with (j,i) exactly once.
If you’d like, I can also explain why this is essentially a transpose operation and how to do it more efficiently. Would you like me to break that part down?