Python - 矩阵中最常见的组合
给定一个矩阵,任务是编写一个Python程序来提取最常见的元素大小大于 2 的任何组合。
例子:
Input: test_list = [[4, 5, 6, 2], [7, 6, 3, 2], [4, 2, 6, 7], [1, 2, 4, 6]]
Output: [(2, 6)]
Explanation: [2, 6] in combination occurs 4 times, maximum of all.
Input: test_list = [[4, 5, 6, 2], [7, 6, 3, 2], [4, 2, 6, 7], [1, 2, 4, 7]]
Output: [(2, 4), (2, 6), (2, 7)]
Explanation: [2, 6], [2, 4] and [2, 7] in combination occur 3 times each, maximum of all.
方法:使用组合() + Counter() + most_common() + 列表推导
在这种情况下,使用组合() ,计数器()计算组合,跟踪每个组合的频率。最后, most_common()用于提取组合出现的最大频率。
Python3
# Python3 code to demonstrate working of
# Most common Combination in Matrix
# import required modules
from collections import Counter
from itertools import combinations
# initializing list
test_list = [[4, 5, 6, 2], [7, 6, 3, 2],
[4, 2, 6, 7], [1, 2, 4, 6]]
# printing original list
print("The original list is : " + str(test_list))
res = Counter()
for sub in test_list:
# ignoring 1 sized substring
if len(sub) < 2:
continue
# sorting for common ordering
sub.sort()
# getting and storing combinations
for size in range(2, len(sub) + 1):
for comb in combinations(sub, size):
res[comb] += 1
# getting most common combinations
res = [cmb for cmb,
cnt in res.items() if cnt == res.most_common(1)[0][1]]
# printing result
print("The Most common combination : " + str(res))
输出:
The original list is : [[4, 5, 6, 2], [7, 6, 3, 2], [4, 2, 6, 7], [1, 2, 4, 6]]
The Most common combination : [(2, 6)]