![](/img/trans.png)
[英]Sorting a nested list by second element of sub list without using built-in sorting functions, loops or recursion
[英]arranging a array without loops list comp or recursion
定義:排列數組 排列數組是一個 dim 2 的數組,形狀是方陣 (NXN),對於矩陣中的每個單元格:A[I,J] > A[I,J+1] AND A[I,J ] > A[I+1,J]
我有一個任務來編寫一個函數:獲取一個 numpy 數組並返回 True 如果 - 給定數組是一個排列數組 False - 否則
注意:我們不能使用循環、列表組合或遞歸。 任務的重點是使用numpy的東西。 假設:我們可以假設數組不為空且沒有 NA,而且所有單元格都是數字
我的代碼不是非常面向 numpy 的..:
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
列比較的結果就是你想要的結果。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.