排列一个没有循环列表组合或递归的数组



定义:排列数组 排列数组是 dim 2 的数组,形状为方阵 (NXN),对于矩阵中的每个单元格:A[I,J]> A[I,J+1] 和 A[I,J]> A[I+1,J]

我有一个任务来写一个功能: 获取一个 numpy 数组并返回 True if - 给定的数组是一个排列数组 错误 - 否则

注意:我们不能使用循环、列表组合或递归。 任务的重点是使用numpy的东西。 假设:我们可以假设数组不为空,没有 NA,所有单元格都是数字

我的代码不是很麻木。

def is_square_ordered_matrix(A):
# Checking if the dimension is 2
if A.ndim != 2:
return False
# Checking if it is a squared matrix
if A.shape[0] != A.shape[1]:
return False
# Saving the original shape to reshape later
originalDim = A.shape
# Making it a dim of 1 to use it as a list
arrayAsList = list((A.reshape((1,originalDim[0]**2)))[0])
# Keeping original order before sorting
originalArray = arrayAsList[:]
# Using the values of the list as keys to see if there are doubles
valuesDictionary = dict.fromkeys(arrayAsList, 1)
# If len is different, means there are doubles and i should return False
if len(arrayAsList) != len(valuesDictionary):
return False
# If sorted list is equal to original list it means the original is already ordered and i should return True
arrayAsList.sort(reverse=True)
if originalArray == arrayAsList:
return True
else:
return False

真实的例子:

is_square_ordered_matrix(np.arange(8,-1,-1).reshape((3,3)))

错误的例子:

is_square_ordered_matrix(np.arange(9).reshape((3,3)))
is_square_ordered_matrix(np.arange(5,-1,-1).reshape((3,2)))

简单比较:

>>> def is_square_ordered_matrix(a):
...     return a.shape[0] == a.shape[1] and np.all(a[:-1] > a[1:]) and np.all(a[:, :-1] > a[:, 1:])
...
>>> is_square_ordered_matrix(np.arange(8,-1,-1).reshape((3,3)))
True
>>> is_square_ordered_matrix(np.arange(9).reshape((3,3)))
False
>>> is_square_ordered_matrix(np.arange(5,-1,-1).reshape((3,2)))
False

首先,将a[:-1]a[1:]进行比较,它将每行的元素与下一行的元素进行比较,然后用np.all来判断:

>>> a = np.arange(8,-1,-1).reshape((3,3))
>>> a[:-1]   # First and second lines
array([[8, 7, 6],
[5, 4, 3]])
>>> a[1:]    # Second and third lines
array([[5, 4, 3],
[2, 1, 0]])
>>> a[:-1] > a[1:]
array([[ True,  True,  True],
[ True,  True,  True]])
>>> np.all(a[:-1] > a[1:])
True

然后将a[:,:-1]a[:, 1:]进行比较,这将比较列:

>>> a[:, :-1]   # First and second columns
array([[8, 7],
[5, 4],
[2, 1]])
>>> a[:, 1:]    # Second and third columns
array([[7, 6],
[4, 3],
[1, 0]])
>>> a[:, :-1] > a[:, 1:]
array([[ True,  True],
[ True,  True],
[ True,  True]])

行比较and列比较的结果是您想要的结果。

最新更新