-1

Please help me with the solution of the problem: in a two-dimensional array, swap the elements located symmetrically relative to the main diagonal.

enter image description here

def obmen():
    for i in range(n-1):
        for j in range(n-i):
            if n-i+1 < j:
                b = A[i][j]
                A[i][j] = A[n-j+1][n-i+1]
                A[n-j+1][n-i+1] = b
    for i in range(n):
        for j in range(n):
            print('%0.3f'%(A[i][j]), end=' ')
        print()
    return A

A = obmen() 
Pranav Hosangadi
  • 23,755
  • 7
  • 44
  • 70

1 Answers1

0

You can flip rows an columns using zip():

# original 5x5 matrix (list of lists):

i = iter(range(10,35))
M = [ list(row) for row in zip((*[i]*5)) ]

print(*M,sep="\n")
[10, 11, 12, 13, 14]
[15, 16, 17, 18, 19]
[20, 21, 22, 23, 24]
[25, 26, 27, 28, 29]
[30, 31, 32, 33, 34]

Transpose using zip():

T = [ list(r) for r in zip(*M) ]

print(*T,sep="\n")
[10, 15, 20, 25, 30]
[11, 16, 21, 26, 31]
[12, 17, 22, 27, 32]
[13, 18, 23, 28, 33]
[14, 19, 24, 29, 34]

Using simple loops, you would append values from each row to the corresponding row in the resulting matrix:

T = []
for row in M:
    for col,value in enumerate(row):
        if len(T) == col:
            T.append([])
        T[col].append(value)

print(*T,sep="\n")
[10, 11, 12, 13, 14]
[15, 16, 17, 18, 19]
[20, 21, 22, 23, 24]
[25, 26, 27, 28, 29]
[30, 31, 32, 33, 34]

If you need the transposition to be done "in-place" you can use indexes for the swaps:

for i in range(5):
    for j in range(i+1,5):
        M[i][j],M[j][i] = M[j][i],M[i][j]
Alain T.
  • 40,517
  • 4
  • 31
  • 51