

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 Questions & Answers
- The most Common POSIX System Calls in Python
- Find most common element in a 2D list in Python
- Combination Sum 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?
- Permutation and Combination in Python?
- How to find the combination of matrix values in R?
- How to get the most common values in array: JavaScript ?
- Find distinct elements common to all rows of a matrix in Python
- Python – Test if all rows contain any common element with other Matrix
- What are most common elevator-related issues that employees face in office buildings?
- Common string operations in Python
- Longest Common Prefix in Python
- Greatest common divisors in Python