Radeen10-_

Rotate Matrix Clockwise/AntiClockwise||Google Interview Question with moderation

Nov 16th, 2021 (edited)
1,079
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.16 KB | None | 0 0
  1. A rotate function that rotates a two-dimensional array (a matrix) either clockwise or anti-clockwise by 90 or 180 degrees with multiple times and returns the rotated array.
  2. The function accepts two parameters: an array, and a string specifying the direction or rotation. The direction will be either "clockwise" or "counter-clockwise".
  3. ==> It can be square matrix or non-square matrix
  4. ==> It can be single row or column
  5.  
  6. Here is examples of how your function will be used:
  7.    
  8. [[1, 2, 3],   | counter-clockwise
  9.  [4, 5, 6],   |            
  10.               | ==========>>>>>>           [[3, 6, 9, 12], [2, 5, 8, 11], [1, 4, 7, 10]]
  11.  [7, 8, 9],   |
  12.  [10,11,12]]  |
  13.  
  14. matrix=[[1, 2, 3],   clockwise
  15.        [4, 5, 6],   =======>>>>   [[7, 4, 1], [8, 5, 2], [9, 6, 3]]
  16.       [7, 8, 9]]
  17. =====================================================================================================================================
  18. @CODE
  19.  
  20. def rotate(matrix,direction):
  21.     if direction == "clockwise":
  22.         return [list(i) for i in zip(*matrix[::-1])]
  23.     elif direction == "counter-clockwise":
  24.         cn_cl = [list(i[::-1]) for i in zip(*matrix[::-1])]
  25.         return cn_cl[::-1]
Add Comment
Please, Sign In to add comment