Python - Formable Strings Count in Matrix
Last Updated :
26 Apr, 2023
Given strings matrix, the task is to write a Python program to count strings that can be made from letters from the given list.
Examples:
Input : test_list = [["gfg", "best"], ["all", "love", "gfg"],
["gfg", "is", "good"], ["geeksforgeeks"]], tar_list = ["g", "f", "s", "b", "o", "d", "e", "t"]
Output : 5
Explanation : gfg, best, gfg, gfg, good are strings that can be formed from target list chars.
Input : test_list = [["gfg", "best"], ["all", "love", "gfg"], ["gfg", "is", "good"],
["geeksforgeeks"]], tar_list = ["g", "f", "s", "b", "d", "e", "t"]
Output : 4
Explanation : gfg, best, gfg, gfg are strings that can be formed from target list chars.
Method #1 : Using loop + all() Method
In this, we perform the task of iterating through the loop using for loop, all() is used to check if each element of string has all the letters from the target list. If found, the counter is incremented.
Python3
# Python3 code to demonstrate working of
# Formable Strings Count in Matrix
# Using loop
# initializing list
test_list = [["gfg", "best"], ["all", "love", "gfg"],
["gfg", "is", "good"], ["geeksforgeeks"]]
# printing original list
print("The original list is : " + str(test_list))
# initializing target list
tar_list = ["g", "f", "s", "b", "o", "d", "e", "t"]
res = 0
for sub in test_list:
for ele in sub:
# checking for all elements present using all()
if all(el in tar_list for el in ele):
res += 1
# printing result
print("The computed count : " + str(res))
OutputThe original list is : [['gfg', 'best'], ['all', 'love', 'gfg'], ['gfg', 'is', 'good'], ['geeksforgeeks']]
The computed count : 5
Time Complexity: O(n*n)
Auxiliary Space: O(n)
In this, the problem is solved in one line using list comprehension, all() is used to check for all characters present and sum() is used to compute the number of strings after strings filtration.
Python3
# Python3 code to demonstrate working of
# Formable Strings Count in Matrix
# Using list comprehension + all() + sum()
# initializing list
test_list = [["gfg", "best"], ["all", "love", "gfg"],
["gfg", "is", "good"], ["geeksforgeeks"]]
# printing original list
print("The original list is : " + str(test_list))
# initializing target list
tar_list = ["g", "f", "s", "b", "o", "d", "e", "t"]
# computing summation using sum()
# list comprehension used to provide one liner solution
res = sum([sum([1 for ele in sub if all(el in tar_list for el in ele)])
for sub in test_list])
# printing result
print("The computed count : " + str(res))
OutputThe original list is : [['gfg', 'best'], ['all', 'love', 'gfg'], ['gfg', 'is', 'good'], ['geeksforgeeks']]
The computed count : 5
Time Complexity: O(n3)
Auxiliary Space: O(n)
Method #3: Using re
Another approach to solve this problem is by using the Python re module. The re module provides functionality to search a string for a pattern and extract the matched text. To solve this problem, we can create a regular expression pattern by concatenating all the characters in the target list, and then search each string in the matrix for this pattern. If a match is found, we increment the count of formable strings.
Here is an implementation of this approach in Python:
Python3
import re
# Initializing list
test_list = [["gfg", "best"], ["all", "love", "gfg"], ["gfg", "is", "good"], ["geeksforgeeks"]]
# Initializing target list
tar_list = "gfsobdet"
# Creating regular expression pattern from target list
pattern = '[' + tar_list + ']+'
# Searching for pattern in each string of the matrix
res = 0
for sub in test_list:
for ele in sub:
if re.fullmatch(pattern, ele):
res += 1
# Printing result
print("The computed count: ", res)
OutputThe computed count: 5
Time complexity: O(n2 * m), where n is the number of strings in the matrix, and m is the average length of the strings.
Auxiliary space: O(n).
Note that this approach is not as efficient as the first two methods, as the regular expression matching can be slower than the other two methods.
Method 4: Use nested for loops and a dictionary to keep track of the frequency of each target character.
Step-by-step approach:
- Initialize a dictionary to keep track of the frequency of each target character.
- Loop through each element in the target list and increment the frequency of that character in the dictionary.
- Initialize a variable to keep track of the count of formable strings, starting with a value of 0.
- Loop through each sublist in the test list.
- For each sublist, loop through each element and check if all of the characters in the element can be formed using the characters in the dictionary. To do this, use another loop to iterate through each character in the element and check if its frequency in the dictionary is greater than 0. If any character cannot be formed, break out of the loop and move on to the next element.
- If all characters can be formed, increment the count of formable strings.
- After looping through all sublists, return the count of formable strings.
Python3
def count_formable_strings(test_list, tar_list):
# Step 1
freq_dict = {}
for char in tar_list:
freq_dict[char] = freq_dict.get(char, 0) + 1
# Step 2
count = 0
# Step 4
for sublist in test_list:
# Step 5
for element in sublist:
for char in element:
if char not in freq_dict or freq_dict[char] == 0:
break
else:
count += 1
# Step 7
return count
# Example inputs and outputs
test_list = [["gfg", "best"], ["all", "love", "gfg"], ["gfg", "is", "good"], ["geeksforgeeks"]]
tar_list = ["g", "f", "s", "b", "o", "d", "e", "t"]
print("The original list is:", test_list)
print("The computed count is:", count_formable_strings(test_list, tar_list))
OutputThe original list is: [['gfg', 'best'], ['all', 'love', 'gfg'], ['gfg', 'is', 'good'], ['geeksforgeeks']]
The computed count is: 5
Time complexity: O(nm*k), where n is the number of sublists in the test list, m is the maximum length of a sublist, and k is the length of the target list.
Auxiliary space: O(k), where k is the length of the target list.
Similar Reads
Python - Combine Strings to Matrix
Sometimes while working with data, we can receive separate data in the form of strings and we need to compile them into Matrix for its further use. This can have applications in many domains. Let's discuss certain ways in which this task can be performed. Method #1 : Using list comprehension + split
4 min read
Python - String Matrix Concatenation
Sometimes, while working with Matrix we can have a problem in which we have Strings and we need a universal concatenation of all the String present in it. Let's discuss certain ways in which this task can be performed. Method #1 : Using list comprehension + join() We can solve this problem using lis
4 min read
Python - Concatenate string rows in Matrix
The problems concerning matrix are quite common in both competitive programming and Data Science domain. One such problem that we might face is of finding the concatenation of rows of matrix in uneven sized matrix. Letâs discuss certain ways in which this problem can be solved. Method #1 : Using joi
3 min read
Python - List Strings frequency in Matrix
Sometimes, while working with Matrix, we can have a problem in which we need to check the frequency of argument Strings from List in each row of Matrix. This is a very peculiar problem and can have usefulness in many domains. Let us discuss certain ways in which this task can be solved. Method #1 :
5 min read
Python - Convert Integer Matrix to String Matrix
Given a matrix with integer values, convert each element to String. Input : test_list = [[4, 5, 7], [10, 8, 3], [19, 4, 6]] Output : [['4', '5', '7'], ['10', '8', '3'], ['19', '4', '6']] Explanation : All elements of Matrix converted to Strings. Input : test_list = [[4, 5, 7], [10, 8, 3]] Output : [
6 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
Python - Double Split String to Matrix
Given a String, perform the double split, 1st for rows, and next for individual elements so that the given string can be converted to a matrix. Examples: Input : test_str = 'Gfg,best*for,all*geeks,and,CS', row_splt = "*", ele_splt = "," Output : [['Gfg', 'best'], ['for', 'all'], ['geeks', 'and', 'CS
6 min read
Python | Case Counter in String
Sometimes, while working with Python String, we can have a problem in which we need to separate the lower and upper case count. This kind of operation can have its application in many domains. Let's discuss certain ways in which this task can be done. Method #1: Using map() + sum() + isupper() + isl
7 min read
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 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 cr
7 min read
Python | Encoding Decoding using Matrix
This article is about how we use the matrix to encode and decode a text message and simple strings. Encoding process : Take a String convert to corresponding number shown below convert to 2D matrix(array). Now we have 2x2 matrix! When we multiply this matrix with encoding matrix we get encoded 2x2 m
4 min read