之前的博文中谈到了 python3 zip的用法 ,现在看看reversed与zip配合,顺时针读取二维数组的方法。
例题
注:例题来自 https://www.codewars.com/kata/snail/python
- 给定一个n*n的矩阵,通过函数 snail()得到按顺时针方向读取的list:
array = [[1,2,3],
[4,5,6],
[7,8,9]]
snail(array) #=> [1,2,3,6,9,8,7,4,5]
即:
[[1–>2–>3],
[4–>5 6],
[7<–8<–9]]- 如果给定的矩阵为0*0,返回[[]]
解法
def snail(array):
#1. Pop top row
#2. Transpose and flip upside-down (same as rotate 90 degrees counter-clockwise)
#3. Go to 1
#and reference:
#http://stackoverflow.com/questions/1655685/traverse-2d-array-in-spiral-pattern-using-recursion
return list(array[0]) + snail(list(reversed(list(zip(*array[1:]))))) if array else []
解题思路是:
1. 先取到矩阵的第一行元素
2. 将去除了第一行元素的矩阵逆时针旋转90度:zip方法或transpose方法进行行列转换之后,再使用reverse方法将矩阵上下倒置
3. 回到第一步
reverse方法
python doc:
reversed(seq)
Return a reverse iterator. seq must be an object which has a reversed() method or supports the sequence protocol (the len() method and the getitem() method with integer arguments starting at 0).
例如:
list(reversed([‘dream’,’a’,’have’,’I’]))
>>>[‘I’, ‘have’, ‘a’, ‘dream’]
需要注意的是: reverse()方法会改变操作对象,如
>>> a = [1,2,3,4]
>>> b = a
>>> b
[1, 2, 3, 4]
>>> b.reverse()
>>> b
[4, 3, 2, 1]
>>> a
[4, 3, 2, 1]
而reversed()不会,如:
>>> a = [1,2,3,4]
>>> a
[1, 2, 3, 4]
>>> b = a
>>> b
[1, 2, 3, 4]
>>> reversed(b)
>>> list(reversed(b))
[4, 3, 2, 1]
>>> a
[1, 2, 3, 4]
>>> b
[1, 2, 3, 4]
参考
http://stackoverflow.com/questions/1655685/traverse-2d-array-in-spiral-pattern-using-recursion
http://stackoverflow.com/questions/726756/print-two-dimensional-array-in-spiral-order