Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Find Common elements in three Lists using Sets - Python
Next article icon

Python Program to Find Most common elements set

Last Updated : 16 May, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a List of sets, the task is to write a Python program tocompare elements with argument set, and return one with maximum matching elements.

Examples:

Input : test_list = [{4, 3, 5, 2}, {8, 4, 7, 2}, {1, 2, 3, 4}, {9, 5, 3, 7}], arg_set = {9, 6, 5, 3}
Output : {9, 3, 5, 7}
Explanation : Resultant set has maximum matching elements.

Input : test_list = [{4, 3, 5, 2}, {8, 4, 7, 2}, {1, 2, 3, 4}, {9, 5, 3, 7}], arg_set = {4, 6, 5, 3}
Output : {2, 3, 4, 5}
Explanation : Resultant set has maximum matching elements.

Method 1: Using loop + set.intersection()

In this, we perform task of getting all the common elements with argument set using intersection(), and get its length using len(), and maximum length and set is compared and updated during iteration.

Python3




# Python3 code to demonstrate working of
# Most common elements set
# Using loop + intersection()
 
# initializing list
test_list = [{4, 3, 5, 2}, {8, 4, 7, 2},
             {1, 2, 3, 4}, {9, 5, 3, 7}]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing arg_set
arg_set = {9, 6, 5, 3}
 
res = set()
max_len = 0
 
for sub in test_list:
     
    # updating max value on occurrence
    if len(sub.intersection(arg_set)) > max_len:
        max_len = len(sub.intersection(arg_set))
        res = sub
 
# printing result
print("Max Set intersection : " + str(res))
 
 

Output:

The original list is : [{2, 3, 4, 5}, {8, 2, 4, 7}, {1, 2, 3, 4}, {9, 3, 5, 7}] Max Set intersection : {9, 3, 5, 7}

Method 2 : Using max() + list comprehension + intersection()

In this, initial step is to check for the lengths of all intersected set results and get maximum using max(). Next, task of getting set which matches required length is extracted.

Python3




# Python3 code to demonstrate working of
# Most common elements set
# Using loop + intersection()
 
# initializing list
test_list = [{4, 3, 5, 2}, {8, 4, 7, 2},
             {1, 2, 3, 4}, {9, 5, 3, 7}]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing arg_set
arg_set = {9, 6, 5, 3}
 
# getting maximum length
max_len = max(len(sub.intersection(arg_set)) for sub in test_list)
 
# getting element matching length
res = [sub for sub in test_list if len(sub.intersection(arg_set)) == max_len][0]
 
# printing result
print("Set intersection : " + str(res))
 
 

Output:

The original list is : [{2, 3, 4, 5}, {8, 2, 4, 7}, {1, 2, 3, 4}, {9, 3, 5, 7}] Max Set intersection : {9, 3, 5, 7}

Method 3: Using Reduce and Lambda Function

Step-by-Step algorithm :

  • Initialize res to the first set in test_list
  • Use reduce() and a lambda function to compare each set in test_list with arg_set based on the number of elements they have in common:
    a. If the current set in test_list has more elements in common with arg_set than res, set res to the current set
    b. Otherwise, keep res as is
  • Return res

Python3




from functools import reduce
 
# initializing list
test_list = [{4, 3, 5, 2}, {8, 4, 7, 2},
             {1, 2, 3, 4}, {9, 5, 3, 7}]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing arg_set
arg_set = {9, 6, 5, 3}
 
# using reduce() + lambda to get max common elements set
res = reduce(lambda x, y: x if len(x.intersection(arg_set)) > len(y.intersection(arg_set)) else y, test_list)
 
# printing result
print("Max Set intersection : " + str(res))
 
 
Output
The original list is : [{2, 3, 4, 5}, {8, 2, 4, 7}, {1, 2, 3, 4}, {9, 3, 5, 7}] Max Set intersection : {9, 3, 5, 7}

Time complexity:  O(n), where n is the number of sets
Auxiliary Space: O(1)

Method 4: Using the heapq module to find the set with the maximum number of common elements

  • Initialize a list common_list with the result of mapping each set in test_list to its intersection with arg_set using the map() function and the set.intersection() method.
  • Initialize a list heap with the negative length of each set in common_list (negated to create a min-heap).
  • Use the heapq.nlargest() function to find the set in test_list with the maximum number of elements in common_list.
  • Return the set with the maximum number of common elements.

Python3




import heapq
 
# initializing list
test_list = [{4, 3, 5, 2}, {8, 4, 7, 2},
             {1, 2, 3, 4}, {9, 5, 3, 7}]
# initializing arg_set
arg_set = {9, 6, 5, 3}
 
# using map() to get common elements
common_list = list(map(lambda s: s.intersection(arg_set), test_list))
 
# using heapq.nlargest() to get set with max common elements
max_common_set = heapq.nlargest(1, test_list, key=lambda s: len(s.intersection(arg_set)))[0]
 
# printing result
print("Max Set intersection : " + str(max_common_set))
 
 
Output
Max Set intersection : {9, 3, 5, 7}

Time complexity: O(n log n), where n is the number of sets in test_list, due to the use of the heapq.nlargest() function.
Auxiliary space: O(n), to store the common_list and heap lists.



Next Article
Find Common elements in three Lists using Sets - Python
author
manjeet_04
Improve
Article Tags :
  • Python
  • Python Programs
  • Python set-programs
Practice Tags :
  • python

Similar Reads

  • Remove common elements from two list in Python
    When working with two lists in Python, we may need to remove the common elements between them. A practical example could be clearing out overlapping tasks between two to-do lists. The most efficient way to remove common elements between two lists is by using sets. [GFGTABS] Python a = [1, 2, 3, 4, 5
    3 min read
  • Python program to Mark duplicate elements in string
    Given a list, the task is to write a Python program to mark the duplicate occurrence of elements with progressive occurrence number. Input : test_list = ['gfg', 'is', 'best', 'gfg', 'best', 'for', 'all', 'gfg'] Output : ['gfg1', 'is', 'best1', 'gfg2', 'best2', 'for', 'all', 'gfg3'] Explanation : gfg
    3 min read
  • Find Common elements in three Lists using Sets - Python
    We are given three lists we need to find common elements in all three lists using sets. For example a = [1, 2, 3, 4], b = [2, 3, 5, 6] and c = [1, 2, 3, 7]. We need to find all common elements so that resultant output should be {2, 3}. Using set.intersection()set.intersection() method finds common e
    3 min read
  • Python - Test Common Elements Order
    Sometimes, while working with lists, we can have a problem in which we need to test if list contains common elements. This type of problem has been dealt many times and has lot of solutions. But sometimes, we might have a problem in which we need to check that those common elements appear in same or
    4 min read
  • Python Program To Get Minimum Elements For String Construction
    Given a String, the task is to write a Python program to count the minimum elements required to form a string from list elements. Input : test_list = ["geek", "ring", "sfor", "ok", "woke"], tar_str = "working" Output : 2 Explanation : working can be formed using woke and ring. Input : test_list = ["
    3 min read
  • Python | Find common elements in list of lists
    The problem of finding the common elements in list of 2 lists is quite a common problem and can be dealt with ease and also has been discussed before many times. But sometimes, we require to find the elements that are in common from N lists. Let's discuss certain ways in which this operation can be
    6 min read
  • Python - Print all common elements of two lists
    Finding common elements between two lists is a common operation in Python, especially in data comparison tasks. Python provides multiple ways to achieve this, from basic loops to set operations. Let's see how we can print all the common elements of two lists Using Set Intersection (Most Efficient)Th
    3 min read
  • Python program to convert a list to a set based on a common element
    Given a list of lists, the task is to write a python program that can convert each sublist to a set and combine to sublists into one set if they have a common element. The output printed will be a list of sets. Input : test_list = [[15, 14, 12, 18], [9, 5, 2, 1], [4, 3, 2, 1], [19, 11, 13, 12]] Outp
    4 min read
  • Python | Print the common elements in all sublists
    Given a list of lists, the task is to find the elements which are common in all sublist. There are various approaches to do this task. Let's discuss the approaches one by one. Method #1: Using set C/C++ Code # Python code to find duplicate element in all # sublist from list of list # List of list in
    3 min read
  • Python | Find most common element in a 2D list
    Given a 2D list (may or may not be of same length), write a Python program to find the most common element in the given 2D list. Examples: Input : [[10, 20, 30], [20, 50, 10], [30, 50, 10]] Output : 10 Input : [['geeks', 'wins'], ['techie', 'wins']] Output : wins Approach #1 : Using max() function F
    5 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences