DEV Community

Gaurav Yadav
Gaurav Yadav

Posted on

Matrices in Python

To solve compute problems we use different type of data structures like array , maps, etc. One such data structure is matrices or 2D arrays. Matrices act as foundation for other data structure like graphs .

Define matrices in python

matrix = [
   [1, 2, 3],
   [4, 5, 6],
   [7, 8, 9]
]
Enter fullscreen mode Exit fullscreen mode

Define a 3x3 matrix in python, row(R) equals 3 and column(C) equals 3

matrix_3x3 = [[0]* 3 for in range(3)]
Enter fullscreen mode Exit fullscreen mode

There are popular problems in matrices:

Transpose a matrix:

def calculate_transpose_of_matrix(mat: list[list]) -> list[list]:
    N = len(mat)
    for i in range(N):
       for j in range(i+1, N):
           mat[i][j], mat[j][i] = mat[j][i], mat[i][j]

   return mat
Enter fullscreen mode Exit fullscreen mode

Print matrix in spiral pattern:

def print_matrix_in_spiral(mat: list[list]) -> list[list]:
    R = len(mat)
    C = len(mat[0])

    top = 0
    left = 0
    bottom = R - 1
    right = C - 1

    while top <= bottom and left <= right:
        for i in range(left, (right + 1)):
            print(mat[top][i], end=" ")
        top += 1
        for i in range(top, (bottom + 1)):
            print(mat[i][right], end=" ")
        right -= 1
        if top <= bottom:
            for i in range(right, (left - 1), -1):
                print(mat[bottom][i], end=" ")
            bottom -= 1
        if left <= right:
            for i in range(bottom, (top - 1), -1):
                print(mat[i][left], end= " ")
            left += 1
Enter fullscreen mode Exit fullscreen mode

Top comments (0)