Rotating a Matrix in Python

Rotating a matrix in python trick :


Let there be a matrix called "img" , and for instance say there is a flag "f" which will determine the type of rotation :
f = 0 --> Left Rotate
f = 1 --> Right Rotate

The method we will implement will work irrespective the size of the matrix and does not have any limiting constraints.

INPUT :  
[ 10 30     
  20 40 ]

if flag f = 1 :
OUTPUT :
[ 20 10 
  40 30 ]
if flag f = 0 :
OUTPUT :
[ 30 40
  10 20 ]

so to perform, the above process on a matrix of dimension n*m :
_
def rotator(img,f):
   rot =[]
   if f==1:
      rot = zip(*img[::-1])
   else:
      rot = zip(*img[::-1])
      rot = zip(*rot[::-1])
      rot = zip(*rot[::-1])
      #what we did was we right rotated 3 times the matrix to get a left rotated matrix

   return rot
_

so how does it work ?

we had img = [[10 30],[20 40 ]]
now lets say f = 1:
img[::-1] --> [[20,40],[10,30]]
*img[::-1] --> [20,40],[10,30]
zip(*img[::-1]) --> zip([20,40],
                        [10,30]) #so 20 and 10 are zipped together 
                                 #and 40 and 30 are zipped together
--> [[20,10]
    ,[40,30]]

Thats it hope it helped 😇

Comments

Popular Posts