Created
October 21, 2024 07:40
-
-
Save Tusenka/d82ab46fdbd135d039a629de10201ccf to your computer and use it in GitHub Desktop.
Python 2d matrix transformation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/python3 | |
import math | |
import os | |
import random | |
import re | |
import sys | |
import copy | |
import pprint | |
# | |
# Complete the 'matrixRotation' function below. | |
# | |
# The function accepts following parameters: | |
# 1. 2D_INTEG<ER_ARRAY matrix | |
# 2. INTEGER r | |
# | |
def rotate(matrix): | |
res=[] | |
M=len(matrix[0]) | |
N=len(matrix) | |
col=0 | |
row=0 | |
i=0 | |
while i<N: | |
j=0 | |
while j<M: | |
if j==0: | |
res.append([]) | |
res[i].append(0) | |
j=j+1 | |
i=i+1 | |
while col < N and row < M: | |
i=row+1; j=col; | |
#rows | |
while j<M-1: | |
res[row][j]=matrix[row][j+1] | |
j=j+1 | |
res[row][M-1]=matrix[row+1][M-1] | |
#last row | |
j=col+1 | |
while j<M: | |
res[N-1][j]=matrix[N-1][j-1] | |
j=j+1 | |
res[N-1][col]=matrix[N-2][col] | |
#columns | |
while i<N-1: | |
res[i][col]=matrix[i-1][col] | |
res[i][M-1]=matrix[i+1][M-1] | |
i=i+1 | |
i=row+1 | |
col=col+1 | |
row=row+1 | |
M=M-1 | |
N=N-1 | |
return res | |
def print_matrix(matrix): | |
for row in matrix: | |
print(' '.join(map(str, row))) | |
def matrixRotation(matrix, r): | |
for i in range(0,r): | |
matrix=rotate(matrix) | |
print_matrix(matrix) | |
if __name__ == '__main__': | |
first_multiple_input = input().rstrip().split() | |
m = int(first_multiple_input[0]) | |
n = int(first_multiple_input[1]) | |
r = int(first_multiple_input[2]) | |
matrix = [] | |
for _ in range(m): | |
matrix.append(list(map(int, input().rstrip().split()))) | |
matrixRotation(matrix, r) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment