Open In App

Python | Nth Column vertical string in Matrix

Last Updated : 09 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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 the same, that too as a string, not merely as a list of characters. This task has its application in gaming in which we need to extract strings during crosswords. Let’s discuss a way in which this task can be performed. 

Method 1: 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))


Output

The original list : [('a', 'g', 'v'), ('e', 'f', 8), ('b', 'g', 0)]
Constructed vertical string : gfg

Time complexity: O(n), where n is the length of the input list test_list. 
Auxiliary space: O(1) because the amount of extra space used is constant and does not depend on the size of the input. Specifically, the only extra space used is for the temp list and the res string, both of which require O(n) space, where n is the length of test_list. 

Method 2: 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

Time complexity: O(n) 
Auxiliary space: O(n)

Method 3: Using for loop:

This method iterates through each tuple in the list and appends the Nth element to a string. Finally, the resulting string is printed as the vertical string.

Python3




# 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 for loop
res = ""
for sub in test_list:
    res += str(sub[N])
 
# Printing result
print("Constructed vertical string : " + str(res))


Output

The original list : [('a', 'g', 'v'), ('e', 'f', 8), ('b', 'g', 0)]
Constructed vertical string : gfg

Time complexity: O(N), where N is the number of tuples in the list. 
Auxiliary Space: O(N), where N is the number of tuples in the list.

Method 4: Iterating through the rows of the matrix and appending the Nth character to a string variable.

In this approach, initialize an empty string variable res and iterate through the rows of the matrix using a for loop. For each row, append the Nth character (i.e., the character at index N) to the res variable. Finally, print the constructed vertical string.

Approach:

  • Initialize a list of tuples test_list that represents the matrix.
  • Print the original list to verify it is correct.
  • Initialize the value of N to the index of the column we want to extract.
  • Initialize an empty string variable res to store the extracted vertical string.
  • Iterate through each row in the test_list matrix using a for loop.
    • For each row, append the Nth character (i.e., the character at index N) to the res variable.
    • After iterating through all rows, print the constructed vertical string
  • Print the res.

Python3




# Python3 code to demonstrate working of
# Nth Column vertical string in Matrix
# Using for loop
 
# 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
 
# Using for loop
res = ''
for row in test_list:
    res += row[N]
 
# Printing result
print("Constructed vertical string : " + str(res))


Output

The original list : [('a', 'g', 'v'), ('e', 'f', 8), ('b', 'g', 0)]
Constructed vertical string : gfg

The time complexity of this approach is O(n), where n is the number of rows in the matrix. 
The auxiliary space complexity is O(1), as we are only using a single string variable to store the result.

Method 5: Using map() and str.join()

Approach:

  1. Initialize the list of tuples with the required values.
  2. Initialize the Nth column value that needs to be extracted.
  3. Use the map() function to extract the Nth column from each tuple.
  4. Convert the map object to a list.
  5. Join the extracted characters using the join() method.
  6. Return the constructed vertical string.
  7. Print the result.

Python3




# Python3 code to demonstrate working of
# Nth Column vertical string in Matrix
# Using map() and join()
 
# 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
 
# Using map() and join()
res = ''.join(list(map(lambda x: x[N], test_list)))
 
# Printing result
print("Constructed vertical string : " + str(res))


Output

The original list : [('a', 'g', 'v'), ('e', 'f', 8), ('b', 'g', 0)]
Constructed vertical string : gfg

Time complexity: O(n), where n is the number of tuples in the list.
Auxiliary space: O(n), where n is the number of tuples in the list.

Method 6: Using pandas library

Here’s another approach that uses the pandas library to extract the Nth column of the input matrix and string concatenation to construct the final vertical string.

Step-by-step approach:

  1. Import the pandas library.
  2. Initialize the input list test_list as a pandas DataFrame.
  3. Initialize the variable N to specify the column index to extract.
  4. Use the iloc attribute of the DataFrame to extract the Nth column as a Series object.
  5. Use the str.cat() method of the Series object to concatenate the elements into a single string.
  6. Print the final vertical string.

Python3




import pandas as pd
 
# initializing list
test_list = [('a', 'g', 'v'), ('e', 'f', 8), ('b', 'g', 0)]
 
# convert list to DataFrame
df = pd.DataFrame(test_list)
 
# initializing Nth column
N = 1
 
# extract Nth column as a Series object
col = df.iloc[:, N]
 
# concatenate elements into a single string
res = col.str.cat()
 
# print final vertical string
print("Constructed vertical string : " + str(res))


OUTPUT:
Constructed vertical string : gfg

Time complexity: O(n), where n is the number of elements in the input list.

Auxiliary space: O(n), to store the elements of the input list as a DataFrame. However, this approach may be more memory-efficient than some of the other methods, especially for very large input lists.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads