【发布时间】:2018-02-21 22:04:16
【问题描述】:
我想旋转(逆时针)一个 2D nxn 整数数组,并且 2D 数组存储为列表列表。
例如:
a = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
旋转后,输出应如下所示:
b = [[3, 6, 9],
[2, 5, 8],
[1, 4, 7]]
我写了一个执行上述旋转的函数:
def rotate_clockwise(matrix):
transposed_matrix = zip(*matrix) # transpose the matrix
return list(map(list, reversed(transposed_matrix))) # reverse the transposed matrix
该函数运行良好,代码在我看来非常 Pythonic。 但是,我无法理解我的解决方案的空间和时间复杂度。
谁能解释一下我所使用的结构的复杂性,即zip(*matrix)、reversed(list)、map(list, iterator) 和list(iterator)?
我怎样才能让这段代码更有效率? 另外,旋转二维矩阵最有效的方法是什么?
注意:正如@Colonder 在 cmets 中所提到的,可能存在与此类似的问题。但是,这个问题更侧重于讨论问题的空间和时间复杂性。
【问题讨论】:
-
@Colonder 我已经阅读了那个帖子,没有提到效率或关于复杂性的讨论。
-
如果您可以使用 numpy,我相信 numpy.rot90 可以满足您的需求。
-
@AaronN.Brock 不,即使我愿意,我也不能!我只能使用标准库功能。
标签: python arrays python-3.x rotation