Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python program to convert a list to a set based on a common element
When you need to group sublists that share common elements, you can convert them to sets and merge those with overlapping elements. This technique uses the union method to combine sets and recursion to handle multiple merges.
Example
Below is a demonstration of merging sublists based on common elements ?
def common_elem_set(my_set):
for index, val in enumerate(my_set):
for j, k in enumerate(my_set[index + 1:], index + 1):
if val & k: # Check if sets have common elements
my_set[index] = val.union(my_set.pop(j))
return common_elem_set(my_set)
return my_set
my_list = [[18, 14, 12, 19], [9, 6, 2, 1], [54, 32, 21, 17], [18, 11, 13, 12]]
print("The list is :")
print(my_list)
my_set = list(map(set, my_list))
my_result = common_elem_set(my_set)
print("The result is :")
print(my_result)
The list is :
[[18, 14, 12, 19], [9, 6, 2, 1], [54, 32, 21, 17], [18, 11, 13, 12]]
The result is :
[{11, 12, 13, 14, 18, 19}, {9, 2, 6, 1}, {32, 17, 21, 54}]
How It Works
The algorithm follows these steps ?
Convert each sublist to a set using
map(set, my_list)Compare each set with all subsequent sets using nested loops
Use the
&operator to check for common elements between setsWhen common elements are found, merge the sets using
union()Remove the merged set and recursively process the updated list
Continue until no more merges are possible
Alternative Approach Using While Loop
Here's a non-recursive version that's easier to understand ?
def merge_common_sets(data):
sets_list = [set(sublist) for sublist in data]
merged = True
while merged:
merged = False
for i in range(len(sets_list)):
for j in range(i + 1, len(sets_list)):
if sets_list[i] & sets_list[j]: # Common elements found
sets_list[i] = sets_list[i].union(sets_list[j])
sets_list.pop(j)
merged = True
break
if merged:
break
return sets_list
my_list = [[18, 14, 12, 19], [9, 6, 2, 1], [54, 32, 21, 17], [18, 11, 13, 12]]
result = merge_common_sets(my_list)
print("Original list:", my_list)
print("Merged sets:", result)
Original list: [[18, 14, 12, 19], [9, 6, 2, 1], [54, 32, 21, 17], [18, 11, 13, 12]]
Merged sets: [{11, 12, 13, 14, 18, 19}, {1, 2, 6, 9}, {17, 21, 32, 54}]
Key Points
The
&operator returns the intersection of two setsThe
union()method combines all elements from both setsRecursion ensures all possible merges are performed
Sets automatically handle duplicate removal
Conclusion
This approach efficiently groups sublists with shared elements by converting them to sets and using set operations. The recursive method ensures all possible merges are completed, resulting in disjoint groups.
