Codewars: Snail

一道4kyu的问题。思路:使用递归可以将按模式遍历分解为外层遍历和内层子问题,逻辑非常自然。为了不将list作为元素添加,要么在添加时使用concat或+=,要么最后flatten展开。

在优秀解答中学习到一个技巧: 使用zip重组调换行列之后reverse等价于矩阵逆时针旋转90度。 博主用了十三行代码实现,优秀解答仅需一行(每次处理一行,列表推导、递归、三元表达式)


Snail Sort
Given an n x n array, return the array elements arranged from outermost elements to the middle element, traveling clockwise.

array = [[1,2,3],
[4,5,6],
[7,8,9]]
snail(array) #=> [1,2,3,6,9,8,7,4,5]
For better understanding, please follow the numbers of the next array consecutively:

array = [[1,2,3],
[8,9,4],
[7,6,5]]
snail(array) #=> [1,2,3,4,5,6,7,8,9]
This image will illustrate things more clearly:

NOTE: The idea is not sort the elements from the lowest value to the highest; the idea is to traverse the 2-d array in a clockwise snailshell pattern.

NOTE 2: The 0x0 (empty matrix) is represented as [[]]


def snail(array):
    if not array:
        return array
    res = list()
    n = len(array)
    res += array.pop(0)
    for i in range(1,n-1):
        res.append(array[i-1].pop())
    if array:
        res += array.pop()[::-1]
    for i in range(n-2,0,-1):
        res.append(array[i-1].pop(0))
    res += snail(array)
    return res

猜你喜欢

转载自blog.csdn.net/qq_35279914/article/details/82191941