Python – Convert Matrix to Sets of Set
Last Updated :
12 Apr, 2023
In this article, the task is to write Python program to Convert Matrix to sets of set.
Examples:
Input : test_list = [[5, 6, 3], [1, 7, 9], [8, 2, 0]]
Output : {frozenset({8, 0, 2}), frozenset({1, 9, 7}), frozenset({3, 5, 6})}
Explanation : Converted to sets of frozensets to remain immutable and hashable.
Input : test_list = [[5, 6, 3], [1, 7, 9]]
Output : {frozenset({1, 9, 7}), frozenset({3, 5, 6})}
Explanation : Converted to sets of frozensets to remain immutable and hashable.
Method #1: Using set() + frozenset() + generator expression
In this, we perform iteration till Matrix in generator expression to get inner sets, and outer container is converted to set using set(). Inner container needs to be hashable, hence has to be frozenset() for creation.
Python3
test_list = [[ 5 , 6 , 3 ], [ 1 , 7 , 9 ], [ 8 , 2 , 0 ]]
print ( "The original list is : " + str (test_list))
res = set ( frozenset (sub) for sub in test_list)
print ( "Converted set Matrix : " + str (res))
|
Output
The original list is : [[5, 6, 3], [1, 7, 9], [8, 2, 0]]
Converted set Matrix : {frozenset({8, 0, 2}), frozenset({1, 9, 7}), frozenset({3, 5, 6})}
Method #2: Using map() + frozenset() + set()
In this, map() is used to extend logic of converting inner containers to frozenset().
Python3
test_list = [[ 5 , 6 , 3 ], [ 1 , 7 , 9 ], [ 8 , 2 , 0 ]]
print ( "The original list is : " + str (test_list))
res = set ( map ( frozenset , test_list))
print ( "Converted set Matrix : " + str (res))
|
Output
The original list is : [[5, 6, 3], [1, 7, 9], [8, 2, 0]]
Converted set Matrix : {frozenset({8, 0, 2}), frozenset({1, 9, 7}), frozenset({3, 5, 6})}
Method #3: Using list comprehension and set
Approach
we will use a nested list comprehension to convert each row to a set, then use set and frozenset to convert the resulting list of sets to a set of frozensets.
Algorithm
1. Use a nested list comprehension to convert each row of the matrix to a set.
2. Use set and frozenset to convert the resulting list of sets to a set of frozensets.
3. Return the set of frozensets.
Python3
def matrix_to_sets(matrix):
set_list = [ set (row) for row in matrix]
return { frozenset (s) for s in set_list}
matrix = [[ 5 , 6 , 3 ], [ 1 , 7 , 9 ], [ 8 , 2 , 0 ]]
print (matrix_to_sets(matrix))
|
Output
{frozenset({8, 0, 2}), frozenset({1, 9, 7}), frozenset({3, 5, 6})}
Time complexity: O(nm), where ‘n’ is the number of rows and ‘m’ is the number of columns in the matrix.
Auxiliary Space: O(nm), since we store all the row sets and frozensets in memory.
Method #4: Using list comprehension and frozenset
Step-by-step approach:
- Initialize an empty list result.
- Loop through each sublist in test_list.
- Convert each sublist to a frozenset using frozenset(sub).
- Append the frozenset to the result list.
- Convert the result list to a set using set(result).
Below is the implementation of the above approach:
Python3
test_list = [[ 5 , 6 , 3 ], [ 1 , 7 , 9 ], [ 8 , 2 , 0 ]]
print ( "The original list is : " + str (test_list))
result = [ frozenset (sub) for sub in test_list]
res = set (result)
print ( "Converted set Matrix : " + str (res))
|
Output
The original list is : [[5, 6, 3], [1, 7, 9], [8, 2, 0]]
Converted set Matrix : {frozenset({8, 0, 2}), frozenset({1, 9, 7}), frozenset({3, 5, 6})}
Time complexity: O(n^2), where n is the number of elements in the matrix, as we need to loop through each element in each sublist.
Auxiliary space: O(n), as we create a list of frozensets with the same number of elements as the original matrix.
Method #5:Using reduce:
Algorithm :
- Import the reduce function from functools module.
- Initialize the list of lists.
- Use reduce function to convert list of lists to set of sets by applying union operation on each frozenset of inner lists.
- The set function is called with an empty set as the initial value to create an empty set.
- Store the result in a variable.
-
- Print the result.
Python3
from functools import reduce
test_list = [[ 5 , 6 , 3 ], [ 1 , 7 , 9 ], [ 8 , 2 , 0 ]]
print ( "The original list is : " + str (test_list))
res = reduce ( lambda x, y: x.union({ frozenset (y)}), test_list, set ())
print ( "Converted set Matrix : " + str (res))
|
Output
The original list is : [[5, 6, 3], [1, 7, 9], [8, 2, 0]]
Converted set Matrix : {frozenset({8, 0, 2}), frozenset({1, 9, 7}), frozenset({3, 5, 6})}
Time complexity: O(nm log m), where n is the number of inner lists and m is the maximum length of the inner lists. The frozenset() function takes O(m log m) time, and reduce() takes O(n) time. Overall, the time complexity of this algorithm is dominated by the time complexity of frozenset() function.
Space complexity: O(nm), where n is the number of inner lists and m is the maximum length of the inner lists. The space complexity is dominated by the space required to store the set of frozensets.
Similar Reads
Python Program to Convert Matrix to String
Program converts a 2D matrix (list of lists) into a single string, where all the matrix elements are arranged in row-major order. The elements are separated by spaces or any other delimiter, making it easy to represent matrix data as a string. Using List ComprehensionList comprehension provides a co
2 min read
How To Create A Set Of Sets In Python?
Sets are flexible data structures in Python that hold distinct items. There are situations in which you may need to construct a set of sets, even though sets are unordered and flexible in and of themselves. In this article, we will see how to create a set of sets. Note: We can't create a set of sets
2 min read
Python program to Convert a Matrix to Sparse Matrix
Converting a matrix to a sparse matrix involves storing only non-zero elements along with their row and column indices to save memory. Using a DictionaryConverting a matrix to a sparse matrix using a dictionary involves storing only the non-zero elements of the matrix, with their row and column indi
2 min read
Python - Convert List of lists to list of Sets
We are given a list containing lists, and our task is to convert each sublist into a set. This helps remove duplicate elements within each sublist. For example, if we have: a = [[1, 2, 1], [1, 2, 3], [2, 2, 2, 2], [0]] The output should be: [{1, 2}, {1, 2, 3}, {2}, {0}] Let's explore some method's t
2 min read
Python Convert Dict of Lists to Dict of Sets
In Python, converting a dictionary of lists to a dictionary of sets is a valuable process for optimizing data structures. This transformation enhances efficiency by eliminating duplicates and enabling efficient membership testing. Utilizing built-in functions like set() and list comprehension simpli
3 min read
Python - Convert Matrix to Dictionary
The task of converting a matrix to a dictionary in Python involves transforming a 2D list or matrix into a dictionary, where each key represents a row number and the corresponding value is the row itself. For example, given a matrix li = [[5, 6, 7], [8, 3, 2], [8, 2, 1]], the goal is to convert it i
4 min read
Python - Convert Integer Matrix to String Matrix
Given a matrix with integer values, convert each element to String. Input : test_list = [[4, 5, 7], [10, 8, 3], [19, 4, 6]] Output : [['4', '5', '7'], ['10', '8', '3'], ['19', '4', '6']] Explanation : All elements of Matrix converted to Strings. Input : test_list = [[4, 5, 7], [10, 8, 3]] Output : [
6 min read
Python | Conversion to N*N tuple matrix
Sometimes, while working with data, we can have a problem in which we have data in form of tuple Matrix with uneven length rows. In this case there's a requirement to complete the N*N matrix with a default value. Let's discuss certain ways in which this problem can be solved. Method #1 : Using loop
5 min read
Convert Dictionary to List of Tuples - Python
Converting a dictionary into a list of tuples involves transforming each key-value pair into a tuple, where the key is the first element and the corresponding value is the second. For example, given a dictionary d = {'a': 1, 'b': 2, 'c': 3}, the expected output after conversion is [('a', 1), ('b', 2
3 min read
Python Program to Convert Tuple Matrix to Tuple List
Given a Tuple Matrix, flatten to tuple list with each tuple representing each column. Example: Input : test_list = [[(4, 5), (7, 8)], [(10, 13), (18, 17)]] Output : [(4, 7, 10, 18), (5, 8, 13, 17)] Explanation : All column number elements contained together. Input : test_list = [[(4, 5)], [(10, 13)]
8 min read