![]() |
VOOZH | about |
Given a String with matrix representation, the task here is to write a python program that converts it to a matrix.
Input : test_str = "[gfg,is],[best,for],[all,geeks]"
Output : [['gfg', 'is'], ['best', 'for'], ['all', 'geeks']]
Explanation : Required String Matrix is converted to Matrix with list as data type.Input : test_str = "[gfg,is],[for],[all,geeks]"
Output : [['gfg', 'is'], ['for'], ['all', 'geeks']]
Explanation : Required String Matrix is converted to Matrix with list as data type.
Method 1 : Using split() and regex expression
In this, a plain list is constructed using appropriate regex expression and split() performs the task of getting inner dimension for 2D Matrix.
Example:
The original string is : [gfg,is],[best,for],[all,geeks] The type of result : <class 'list'> Converted Matrix : [['gfg', 'is'], ['best', 'for'], ['all', 'geeks']]
Method 2 : Using json.loads()
In this, the task of conversion to the matrix is done using the unbuilt method of loads() of JSON library.
Example:
The original string is : [["gfg", "is"], ["best", "for"], ["all", "geeks"]] The type of result : <class 'list'> Converted Matrix : [['gfg', 'is'], ['best', 'for'], ['all', 'geeks']]
Method 3: Using string manipulation and list comprehension
We can use string manipulation to extract the individual elements of the matrix, and then use a list comprehension to create a new matrix with those elements.
Algorithm:
1. Remove the square brackets from the string using string manipulation.
2. Split the string into rows using the comma and newline characters as delimiters.
3. Split each row into its individual elements using the comma as a delimiter.
4. Create a new matrix with the elements using a list comprehension.
[['gfg', 'is'], ['best', 'for'], ['all', 'geeks']]
Time complexity: O(n)
Space complexity: O(n)
Method 4: Use a combination of re.findall() and re.split() functions from the re module.
Step-by-step approach:
[['gfg', 'is'], ['best', 'for'], ['all', 'geeks']]
Time complexity: O(n), where n is the length of the input string.
Auxiliary space: O(n), where n is the length of the input string.