Python - 按 K 大小的子数组最大和对矩阵进行排序
给定矩阵,编写一个Python程序,按 K 大小的子数组和的最大值对行进行排序。
例子:
Input : test_list = [[4, 3, 5, 2, 3], [6, 4, 2, 1, 1], [4, 3, 9, 3, 9], [5, 4, 3, 2, 1]], K = 3
Output : [[4, 3, 5, 2, 3], [6, 4, 2, 1, 1], [5, 4, 3, 2, 1], [4, 3, 9, 3, 9]]
Explanation : 12 = 12 = 12 < 21, is order of maximum sum 3 length substring.
Input : test_list = [[4, 3, 5, 2, 3], [4, 3, 9, 3, 9], [5, 4, 3, 2, 1]], K = 3
Output : [[4, 3, 5, 2, 3], [5, 4, 3, 2, 1], [4, 3, 9, 3, 9]]
Explanation : 12 = 12 < 21, is order of maximum sum 3 length substring.
方法 #1:使用max() + sum() +切片+ sort()
在此,使用 max()、sum() 和切片使用外部函数计算 K 长度子数组的最大值,使用 sort() 完成就地排序。
Python3
# Python3 code to demonstrate working of
# Sort Matrix by K Sized Subarray Maximum Sum
# Using max() + sum() + slicing + sort()
def max_ksub(row):
# getting maximum K length sum
return max(sum(row[idx: idx + K]) for idx in range(len(row) - K))
# initializing list
test_list = [[4, 3, 5, 2, 3], [6, 4, 2, 1, 1],
[4, 3, 9, 3, 9], [5, 4, 3, 2, 1]]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 3
# performing inplace sorting
test_list.sort(key=max_ksub)
# printing result
print("The sorted result : " + str(test_list))
Python3
# Python3 code to demonstrate working of
# Sort Matrix by K Sized Subarray Maximum Sum
# Using sorted() + lambda + max() + sum() + slicing
# initializing list
test_list = [[4, 3, 5, 2, 3], [6, 4, 2, 1, 1],
[4, 3, 9, 3, 9], [5, 4, 3, 2, 1]]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 3
# sorted() performs inplace sort
# lambda function injects comparison logic
res = sorted(test_list, key=lambda row: max(
sum(row[idx: idx + K]) for idx in range(len(row) - K)))
# printing result
print("The sorted result : " + str(res))
输出:
The original list is : [[4, 3, 5, 2, 3], [6, 4, 2, 1, 1], [4, 3, 9, 3, 9], [5, 4, 3, 2, 1]]
The sorted result : [[4, 3, 5, 2, 3], [6, 4, 2, 1, 1], [5, 4, 3, 2, 1], [4, 3, 9, 3, 9]]
方法 #2:使用sorted() + lambda + max() + sum() + 切片
在这里,我们使用 sorted() + lambda函数执行排序任务,该函数注入比较器逻辑并避免调用外部函数。
蟒蛇3
# Python3 code to demonstrate working of
# Sort Matrix by K Sized Subarray Maximum Sum
# Using sorted() + lambda + max() + sum() + slicing
# initializing list
test_list = [[4, 3, 5, 2, 3], [6, 4, 2, 1, 1],
[4, 3, 9, 3, 9], [5, 4, 3, 2, 1]]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 3
# sorted() performs inplace sort
# lambda function injects comparison logic
res = sorted(test_list, key=lambda row: max(
sum(row[idx: idx + K]) for idx in range(len(row) - K)))
# printing result
print("The sorted result : " + str(res))
输出:
The original list is : [[4, 3, 5, 2, 3], [6, 4, 2, 1, 1], [4, 3, 9, 3, 9], [5, 4, 3, 2, 1]]
The sorted result : [[4, 3, 5, 2, 3], [6, 4, 2, 1, 1], [5, 4, 3, 2, 1], [4, 3, 9, 3, 9]]