Matrices
Matrices
1. Product of 2 Matrices
Question:
Given two matrices, compute their product if matrix multiplication is valid (number of columns in the first
matrix equals the number of rows in the second matrix). Otherwise, return an error.
Code:
# Matrix multiplication
for i in range(r1):
for j in range(c2):
for k in range(c1): # or k in range(r2), since M1 == N2
res[i][j] += mat1[i][k] * mat2[k][j]
2. Rotation of Matrix
Question:
Rotate a square matrix 90 degrees clockwise.
Code:
t = int(input())
for c in range(1, t+1):
n = int(input())
mat = []
for i in range(n):
mat.append(list(map(int, input().split())))
rot(mat, n)
print(f"Test Case #{c}:")
for r in mat:
print(*r)
3. Diagonal Traversal of Matrix
Question:
Given a square matrix, compute the sums of all diagonals (both positive and negative slopes) and print them
in reverse order.
Code:
t = int(input())
for _ in range(1, t+1):
n = int(input())
mat = []
for i in range(n):
mat.append(list(map(int, input().split())))
res = diag(mat, n)
print(*res)
Question:
Given a square matrix, print its elements in spiral order starting from the top-left corner.
Code:
t = int(input())
for _ in range(t):
n = int(input())
mat = []
for i in range(n):
mat.append(list(map(int, input().split())))
result = spiral(mat, n)
print(*result)