Python - Most common Combination in Matrix


When it is required to find the most common combination in a matrix, a simple iteration, along with the ‘sort’ method and ‘Counter’ method is used.

Example

Below is a demonstration of the same

from collections import Counter
from itertools import combinations

my_list = [[31, 25, 77, 82], [96, 15, 23, 32]]

print("The list is :")
print(my_list)

my_result = Counter()

for elem in my_list:
   if len(elem) < 2:
      continue

   elem.sort()

   for size in range(2, len(elem) + 1):
      for comb in combinations(elem, size):
         my_result[comb] += 1

my_result = [elem for elem, my_count in my_result.items() if my_count ==
my_result.most_common(1)[0][1]]

print("The result is :")
print(my_result)

Output

The list is :
[[31, 25, 77, 82], [96, 15, 23, 32]]
The result is :
[(15, 23, 32, 96), (25, 31), (25, 82), (15, 32), (23, 32), (15, 32, 96), (25, 31, 82), (15, 23), (25, 77), (15, 23, 32), (25, 77, 82), (32, 96), (31, 77, 82), (15, 96), (31, 77), (23, 96), (25, 31, 77, 82), (31, 82), (77, 82), (23, 32, 96), (15, 23, 96), (25, 31, 77)]

Explanation

  • The required packages are imported into the environment.

  • A list of list is defined and is displayed on the console.

  • A counter is assigned to a variable.

  • The list is iterated over.

  • A condition is placed to check if the length of the element is less than 2.

  • If so, the execution continues.

  • Otherwise, the elements in the list are sorted using the ‘sort’ method.

  • The list is again iterated, and the ‘combinations’ method is used to increment the element at a specific index by 1.

  • Next, list comprehension is used to check if the count is same.

  • This is assigned to a variable.

  • It is displayed as output on the console.

Updated on: 15-Sep-2021

190 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements