Python | Nth Column vertical string in Matrix
Last Updated :
09 Apr, 2023
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))
OutputThe 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))
OutputThe 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))
OutputThe 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:
- Initialize the list of tuples with the required values.
- Initialize the Nth column value that needs to be extracted.
- Use the map() function to extract the Nth column from each tuple.
- Convert the map object to a list.
- Join the extracted characters using the join() method.
- Return the constructed vertical string.
- 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))
OutputThe 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:
- Import the pandas library.
- Initialize the input list test_list as a pandas DataFrame.
- Initialize the variable N to specify the column index to extract.
- Use the iloc attribute of the DataFrame to extract the Nth column as a Series object.
- Use the str.cat() method of the Series object to concatenate the elements into a single string.
- 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.
Similar Reads
Python Tutorial - Learn Python Programming Language Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly. It'sA high-level language, used in web development, data science, automation, AI and more.Known fo
10 min read
Python Interview Questions and Answers Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read
Python OOPs Concepts Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read
Python Projects - Beginner to Advanced Python is one of the most popular programming languages due to its simplicity, versatility, and supportive community. Whether youâre a beginner eager to learn the basics or an experienced programmer looking to challenge your skills, there are countless Python projects to help you grow.Hereâs a list
10 min read
Python Exercise with Practice Questions and Solutions Python Exercise for Beginner: Practice makes perfect in everything, and this is especially true when learning Python. If you're a beginner, regularly practicing Python exercises will build your confidence and sharpen your skills. To help you improve, try these Python exercises with solutions to test
9 min read
Python Programs Practice with Python program examples is always a good choice to scale up your logical understanding and programming skills and this article will provide you with the best sets of Python code examples.The below Python section contains a wide collection of Python programming examples. These Python co
11 min read
Python Introduction Python was created by Guido van Rossum in 1991 and further developed by the Python Software Foundation. It was designed with focus on code readability and its syntax allows us to express concepts in fewer lines of code.Key Features of PythonPythonâs simple and readable syntax makes it beginner-frien
3 min read
Python Data Types Python Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming, Python data types are classes and variables are instances (objects) of thes
9 min read
Input and Output in Python Understanding input and output operations is fundamental to Python programming. With the print() function, we can display output in various formats, while the input() function enables interaction with users by gathering input during program execution. Taking input in PythonPython input() function is
8 min read
Enumerate() in Python enumerate() function adds a counter to each item in a list or other iterable. It turns the iterable into something we can loop through, where each item comes with its number (starting from 0 by default). We can also turn it into a list of (number, item) pairs using list().Let's look at a simple exam
3 min read