Python - Character coordinates in Matrix
Last Updated :
16 May, 2023
Sometimes, while working with Python data, we can have a problem in which we need to extract all the coordinates in Matrix, which are characters. This kind of problem can have potential application in domains such as web development and day-day programming. Let's discuss certain ways in which this task can be performed.
Input : test_list = ['1G', '12F', '231G']
Output : [(0, 1), (1, 2), (2, 3)]
Input : test_list = ['G', 'F', 'G']
Output : [(0, 0), (1, 0), (2, 0)]
Method #1 : Using enumerate() + list comprehension + isalpha() The combination of above functions can be used to solve this problem. In this, we perform the task of working with indices using enumerate and characters filtering is done using isalpha().
Python3
# Python3 code to demonstrate working of
# Character coordinates in Matrix
# Using enumerate() + list comprehension + isalpha()
# initializing list
test_list = ['23f45.;4d', '5678d56d', '789', '5678g']
# printing original list
print("The original list is : " + str(test_list))
# Character coordinates in Matrix
# Using enumerate() + list comprehension + isalpha()
res = [(x, y) for x, val in enumerate(test_list)
for y, chr in enumerate(val) if chr.isalpha()]
# printing result
print("Character indices : " + str(res))
Output : The original list is : ['23f45.;4d', '5678d56d', '789', '5678g']
Character indices : [(0, 2), (0, 8), (1, 4), (1, 7), (3, 4)]
Time Complexity: O(n*n) where n is the number of elements in the list “test_list”. enumerate() + list comprehension + isalpha() performs n*n number of operations.
Auxiliary Space: O(n), extra space is required where n is the number of elements in the list
Method #2 : Using regex() + loop The combination of above functions can be used to solve this problem. In this, we perform task of filtering alphabets using regex expressions. Just returns the first occurrence of character in each string.
Python3
# Python3 code to demonstrate working of
# Character coordinates in Matrix
# Using regex() + loop
import re
# initializing list
test_list = ['23f45.;4d', '5678d56d', '789', '5678g']
# printing original list
print("The original list is : " + str(test_list))
# Character coordinates in Matrix
# Using regex() + loop
res = []
for key, val in enumerate(test_list):
temp = re.search('([a-zA-Z]+)', val)
if temp :
res.append((key, temp.start()))
# printing result
print("Character indices : " + str(res))
Output : The original list is : ['23f45.;4d', '5678d56d', '789', '5678g']
Character indices : [(0, 2), (1, 4), (3, 4)]
Method 3: Using itertools.product()
In this method, we can use the itertools.product() method to generate all possible (x,y) coordinates for the matrix. We can then use list comprehension to filter out the coordinates where the corresponding character is an alphabet.
Python3
# Python3 code to demonstrate working of
# Character coordinates in Matrix
# Using itertools.product()
from itertools import product
# initializing list
test_list = ['23f45.;4d', '5678d56d', '789', '5678g']
# printing original list
print("The original list is : " + str(test_list))
# Character coordinates in Matrix
# Using itertools.product()
n = max(len(s) for s in test_list)
res = [(x, y) for x, y in product(range(len(test_list)), range(n))
if y < len(test_list[x]) and test_list[x][y].isalpha()]
# printing result
print("Character indices : " + str(res))
OutputThe original list is : ['23f45.;4d', '5678d56d', '789', '5678g']
Character indices : [(0, 2), (0, 8), (1, 4), (1, 7), (3, 4)]
Time complexity: O(mn) where m is the number of strings and n is the maximum length of the strings.
Auxiliary space: O(1) since we're not using any extra data structures.
Method #4: Using map() and filter()
Use map() and filter() functions to solve this problem. map() is a built-in Python function that applies a given function to each element of an iterable and returns an iterator with the results. filter() is another built-in Python function that filters out elements from an iterable that do not satisfy a given condition.
Step-by-step approach:
- Define a lambda function that takes a tuple (i, j) as input and returns test_list[i][j] (the character at position (i, j) in test_list).
- Use the map() function to apply the lambda function to all the tuples (i, j) in the Cartesian product of the ranges range(len(test_list)) and range(max(len(s) for s in test_list))).
- Use the filter() function to keep only the tuples (i, j) for which test_list[i][j] is an alphabet.
- Return the filtered tuples as a list.
Python3
# Python3 code to demonstrate working of
# Character coordinates in Matrix
# Using map() and filter()
from itertools import product
# initializing list
test_list = ['23f45.;4d', '5678d56d', '789', '5678g']
# printing original list
print("The original list is : " + str(test_list))
# Character coordinates in Matrix
# Using map() and filter()
res = list(filter(lambda x: x[1] < len(test_list[x[0]]) and test_list[x[0]][x[1]].isalpha(),
map(lambda x: (x[0], x[1]), product(range(len(test_list)), range(max(len(s) for s in test_list))))))
# printing result
print("Character indices : " + str(res))
OutputThe original list is : ['23f45.;4d', '5678d56d', '789', '5678g']
Character indices : [(0, 2), (0, 8), (1, 4), (1, 7), (3, 4)]
Time complexity: O(n^2), where n is the length of the longest string in the list.
Auxiliary space: O(n^2), where n is the length of the longest string in the list (for creating the Cartesian product).
Similar Reads
Python - Convert Matrix to Coordinate Dictionary
Sometimes, while working with Python dictionaries, we can have problem in which we need to perform the conversion of matrix elements to their coordinate list. This kind of problem can come in many domains including day-day programming and competitive programming. Lets discuss certain ways in which t
3 min read
Python - Convert Coordinate Dictionary to Matrix
Sometimes, while working with Python Matrix, we can have problem in which we have dictionary records with key as matrix position and its value, and we wish to convert that to actual Matrix. This can have applications in many domains including competitive programming and day-day programming. Lets dis
4 min read
Python | String List to Column Character Matrix
Sometimes, while working with Python lists, we can have a problem in which we need to convert the string list to Character Matrix where each row is String list column. This can have possible application in data domains. Lets discuss certain ways in which this task can be performed. Method #1 : Using
5 min read
Python - Convert Strings to Character Matrix
Sometimes, while dealing with String lists, we can have a problem in which we need to convert the Strings in list to separate character list. Overall converting into Matrix. This can have multiple applications in data science domain in which we deal with lots of data. Lets discuss certain ways in wh
3 min read
Convert Character Matrix to single String - Python
In this article, we will explore various methods to convert character matrix to single string in Python. The simplest way to do is by using a loop.Using a LoopWe can use a loop (for loop) to iterate through each sublist and concatenate the elements of each sublist and then combine them into a final
2 min read
Python - Convert String to matrix having K characters per row
Given a String, convert it to Matrix, having K characters in each row. Input : test_str = 'GeeksforGeeks is best', K = 7 Output : [['G', 'e', 'e', 'k', 's', 'f', 'o'], ['r', 'G', 'e', 'e', 'k', 's', ' '], ['i', 's', ' ', 'b', 'e', 's', 't']] Explanation : Each character is assigned to 7 element row
9 min read
Character Indices Mapping in String List - Python
We are given a string list we need to map characters to their indices. For example, a = ["hello", "world"] so that output should be [[('h', 0), ('e', 1), ('l', 2), ('l', 3), ('o', 4)], [('w', 0), ('o', 1), ('r', 2), ('l', 3), ('d', 4)]].Using a nested for loopA nested for loop iterates through each
3 min read
Python - Matrix creation of n*n
Matrices are fundamental structures in programming and are widely used in various domains including mathematics, machine learning, image processing, and simulations. Creating an nÃn matrix efficiently is an important step for these applications. This article will explore multiple ways to create such
3 min read
Add custom borders to matrix in Python
Given a Matrix, the task is to write a python program to print each row having custom borders. Input : test_list = [[4, 5, 6], [1, 4, 5], [6, 9, 1], [0, 3 ,1]], bord = "|" Output : | 4 5 6 | | 1 4 5 | | 6 9 1 | | 0 3 1 | Explanation : Matrix is ended using | border as required.Input : test_list = [[
5 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