
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
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.
- Related Articles
- The most Common POSIX System Calls in Python
- Find most common element in a 2D list in Python
- Most Common Flags Used in /proc/cpuinfo
- Combination Sum in Python
- Find distinct elements common to all rows of a matrix in Python
- The Most Common Email Marketing Mistakes
- Name the most common fire extinguisher.
- Why is lightning most common in rainy season?
- How to find the combination of matrix values in R?
- Permutation and Combination in Python?
- What are the most common teenage problems?
- What are the most common mental illnesses?
- Which is the most common lost article in India?
- Python – Test if all rows contain any common element with other Matrix
- 9 Most Common Triggers for Bipolar Mood Episodes
