Python | Nth Column vertical string in Matrix
Sometimes, while working with Python Matrix, we can have a problem in which we need to access the Matrix in vertical form and extract strings from same, that too as a string, not merely as a list of characters. This task has it’s application in gaming in which we need to extract string during crosswords. Let’s discuss a way in which this task can be performed.
Method : Using list comprehension + join() We achieve the task in this method in 2 steps. In 1st step the Nth column elements are extracted using list comprehension. In 2nd step, these elements are joined together to perform the characters to string conversion.
Python3
# Python3 code to demonstrate working of # Nth Column vertical string in Matrix # Using join() + list comprehension # initializing list test_list = [( 'a' , 'g' , 'v' ), ( 'e' , 'f' , 8 ), ( 'b' , 'g' , 0 )] # printing list print ( "The original list : " + str (test_list)) # initializing Nth column N = 1 # Nth Column vertical string in Matrix # Using join() + list comprehension temp = [sub[N] for sub in test_list] res = "".join(temp) # Printing result print ( "Constructed vertical string : " + str (res)) |
The original list : [('a', 'g', 'v'), ('e', 'f', 8), ('b', 'g', 0)] Constructed vertical string : gfg
Method : Using numpy()
Note: Install numpy module using command “pip install numpy”
Another approach could be using numpy, which can extract the Nth column of a matrix as a numpy array and then use numpy.array2string() to convert the array to a string. This approach would have a time complexity of O(n) where n is the number of rows in the matrix, and a space complexity of O(n) as well, as it requires a new numpy array to be created.
Python3
import numpy as np test_matrix = np.array([[ 'a' , 'g' , 'v' ], [ 'e' , 'f' , 8 ], [ 'b' , 'g' , 0 ]]) #initializing Nth column N = 1 # Extracting Nth column temp = test_matrix[:, N] # Converting numpy array to string # Printing result print ( "Constructed vertical string : " + "".join(temp)) |
Output:
Constructed vertical string : gfg
This approach using numpy would have O(n) time complexity and O(n) Auxiliary space as well.
Please Login to comment...