![]() |
VOOZH | about |
Given multiple sets list, the task is to write a Python program to find union of each set.
Examples:
Input : test_list = [{4, 3, 5, 2}, {8, 4, 7, 2}, {1, 2, 3, 4}, {9, 5, 3, 7}]
Output : {1, 2, 3, 4, 5, 7, 8, 9}
Explanation : All elements from all sets included. Duplicates removed.
Input : test_list = [{4, 3, 5, 2}, {8, 4, 7, 2}, {1, 2, 3, 4}]
Output : {1, 2, 3, 4, 5, 7, 8}
Explanation : All elements from all sets included. Duplicates removed.
Method #1 : Using union() + * operator
In this, we perform task of getting union using union(), and * operator is used to perform task of packing all the sets together.
The original list is : [{2, 3, 4, 5}, {8, 2, 4, 7}, {1, 2, 3, 4}, {9, 3, 5, 7}]
Multiple set union : {1, 2, 3, 4, 5, 7, 8, 9}
Time Complexity: O(n*m) where n is the number of sets in the test_list and m is the average number of elements in each set.
Auxiliary Space: O(m), where m is the average number of elements in each set. This is because the program creates a new set, that has the union of all the elements in the sets in test_list, and the space occupied by this set is m.
Method #2 : Using chain.from_iterable() + * operator
In this, we perform task of union, which in turn is flattening using from_iterable().
The original list is : [{2, 3, 4, 5}, {8, 2, 4, 7}, {1, 2, 3, 4}, {9, 3, 5, 7}]
Multiple set union : {1, 2, 3, 4, 5, 7, 8, 9}
Method #3 : Using Counter() function
The original list is : [{2, 3, 4, 5}, {8, 2, 4, 7}, {1, 2, 3, 4}, {9, 3, 5, 7}]
Multiple set union : [1, 2, 3, 4, 5, 7, 8, 9]
Time Complexity: O(n)
Auxiliary Space: O(n)
Method #4: Using update() method
The original list is : [{2, 3, 4, 5}, {8, 2, 4, 7}, {1, 2, 3, 4}, {9, 3, 5, 7}]
Multiple set union : [1, 2, 3, 4, 5, 7, 8, 9]
Time Complexity: O(n)
Auxiliary Space: O(1)
Method #5: Using reduce() method:
The original list is : [{2, 3, 4, 5}, {8, 2, 4, 7}, {1, 2, 3, 4}, {9, 3, 5, 7}]
Multiple set union : {1, 2, 3, 4, 5, 7, 8, 9}
Time Complexity: O(n)
Auxiliary Space: O(n)
Method #6: Using set.update() method
The original list is : [{2, 3, 4, 5}, {8, 2, 4, 7}, {1, 2, 3, 4}, {9, 3, 5, 7}]
The union of multiple sets: {1, 2, 3, 4, 5, 7, 8, 9}
Time Complexity: O(n)
Auxiliary Space: O(n)