Open In App

Python – Formable Strings Count in Matrix

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

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


Output

The 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)

Method #2: Using list comprehension + all() + sum()

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))


Output

The 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)


Output

The 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))


Output

The 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. 



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads