Rotate Image

Rotate Image

You are given an n x n 2D matrix representing an image.

Rotate the image by 90 degrees (clockwise).

Note:

You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation.

Clean Most Pythonic - 24ms

1
2
3
4
5
6
7
class Solution(object):
def rotate(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: void Do not return anything, modify matrix in-place instead.
"""
matrix[:] = map(list, zip(*matrix[::-1]))

test code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
In [13]: m = [
...: [ 5, 1, 9,11],
...: [ 2, 4, 8,10],
...: [13, 3, 6, 7],
...: [15,14,12,16]
...: ]
In [14]: zip(*m)
Out[14]: [(5, 2, 13, 15), (1, 4, 3, 14), (9, 8, 6, 12), (11, 10, 7, 16)]
In [15]: m[::-1]
Out[15]: [[15, 14, 12, 16], [13, 3, 6, 7], [2, 4, 8, 10], [5, 1, 9, 11]]
In [16]: zip(*m[::-1])
Out[16]: [(15, 13, 2, 5), (14, 3, 4, 1), (12, 6, 8, 9), (16, 7, 10, 11)]
In [17]: map(list, zip(*m[::-1]))
Out[17]: [[15, 13, 2, 5], [14, 3, 4, 1], [12, 6, 8, 9], [16, 7, 10, 11]]
In [18]: m[:] = zip(*m[::-1])
In [18]: m[:] = zip(*m[::-1])
In [19]: m
Out[19]: [(15, 13, 2, 5), (14, 3, 4, 1), (12, 6, 8, 9), (16, 7, 10, 11)]

ref

This syntax is a slice assignment. A slice of [:] means the entire list. The difference between nums[:] = and nums = is that the latter doesn’t replace elements in the original list. This is observable when there are two references to the list

1
2
3
4
5
>>> a = list(range(10))
>>> b = a
>>> a[:] = [0, 0, 0] # changes what a and b both refer to
>>> b
[0, 0, 0]

To see the difference just remove the [:] from the above sequence.

1
2
3
4
5
>>> a = list(range(10))
>>> b = a
>>> a = [0, 0, 0] # a now refers to a different list than b
>>> b
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

What does colon at assignment for list[:] = […] do in Python [duplicate]

leet code