15,917,568 members
1.00/5 (1 vote)
See more:
Write a function rotate(m) that takes a list representation m of a square matrix as input, and returns the matrix obtained by rotating the original matrix clockwize by 90 degrees. For instance, if we rotate the matrix above, we get

the matrix is n*n

>>> rotate([[1,2,3],[4,5,6],[7,8,9]])
[[7, 4, 1], [8, 5, 2], [9, 6, 3]]

>>> rotate([[1,1,1],[2,2,2],[3,3,3]])
[[3, 2, 1], [3, 2, 1], [3, 2, 1]]

What I have tried:

Python
```def rotate(m):
l1=m[::]
n=len(m)-1
count=n
for i in range(n+1):
for j in range(n+1):
l1[j][count]=l1[i][j]
count-=1
return l1```
Posted
Updated 12-Aug-19 22:11pm
v2
Pranav Sharma 13-Aug-19 2:53am
all the loops have proper indentations, they are not showing up in the code

## Solution 1

So ... imagine you were the matrix. What do you think happens to you when you run that code on yourself?

Let's make it easier: you are a one dimensional array, and you want to reverse yourself:
`1, 2, 3, 4`

When you do this:
Python
```for i in range(4)
me[3-i] = me[i]```
What do you get?
is it
`4, 3, 2, 1`
Or
`1, 2, 2, 1`

To reverse the array, don't you need to swap the elements?
Python
```for i in range(4)
temp = me[3-i]
me[3-i] = me[i]
me[i] = temp```

Richard Deeming 13-Aug-19 11:32am
Except your final code will reverse the array twice, leaving you with the original array.

Or was than intended as an "exercise for the reader"? :)
OriginalGriff 13-Aug-19 11:45am
You gotta leave 'em something to do! :laugh:

## Solution 2

Your code replace elements of matrix on itself:
Python
`l1[j][count]=l1[i][j]`

this means that
```123 121 121 121
456 456 452 452
789 789 789 781```

So first you kill the 3, then you kill the 6, and you kill the 9 with the 1 that was 3 at beginning.
Try something like
Python
`l1[j][count]=m[i][j]`

at least, it will not kill some elements.

v2