Python Program to Extract Strings with at least given number of characters from other list
Last Updated :
16 May, 2023
Given a list containing only string elements, the task is to write a Python program to extract all the strings which have characters from another list given a number of times.
Examples:
Input : test_list = ["Geeksforgeeks", "is", "best", "for", "geeks"],
char_list = ['e', 't', 's', 'm', 'n'], K = 2
Output : ['Geeksforgeeks', 'best', 'geeks']
Explanation : is has 1, for has 0 characters from list, hence omitted.
Input : test_list = ["Geeksforgeeks", "is", "best", "for", "geeks"],
char_list = ['t', 's', 'm', 'n'], K = 2
Output : ['Geeksforgeeks', 'best']
Explanation : Geeksforgeeks has 2 s, and best has 2 elements from character list.
Method 1: Using list comprehension and sum()
In this, we perform an iteration of characters using list comprehension and sum() is used to check for matching characters sum, which, if found greater than K, is added to result list.
Python3
# initializing list
test_list = ["Geeksforgeeks", "is", "best", "for", "geeks"]
# printing original list
print("The original list is : " + str(test_list))
# initializing characters list
char_list = ['e', 't', 's', 'm', 'n']
# initializing K
K = 2
# sum() computes matching elements frequency
res = [ele for ele in test_list if sum(ch in char_list for ch in ele) >= K]
# printing result
print("Filtered Strings : " + str(res))
OutputThe original list is : ['Geeksforgeeks', 'is', 'best', 'for', 'geeks']
Filtered Strings : ['Geeksforgeeks', 'best', 'geeks']
Time Complexity: O(n2)
Auxiliary Space: O(n)
Method 2 : Using filter(), lambda and sum()
In this, the task of filtering is performed using filter(), rest all the functionalities is performed using similar constructs as above method.
Program:
Python3
# initializing list
test_list = ["Geeksforgeeks", "is", "best", "for", "geeks"]
# printing original list
print("The original list is : " + str(test_list))
# initializing characters list
char_list = ['e', 't', 's', 'm', 'n']
# initializing K
K = 2
# sum() computes matching elements frequency
# filter() used for task of filtering
res = list(filter(lambda ele: sum(ch in char_list for ch in ele) >= K, test_list))
# printing result
print("Filtered Strings : " + str(res))
OutputThe original list is : ['Geeksforgeeks', 'is', 'best', 'for', 'geeks']
Filtered Strings : ['Geeksforgeeks', 'best', 'geeks']
Time Complexity: O(n2) (loop+filter)
Auxiliary Space: O(n)
Approach 3: Using Counter and List Comprehension
This method uses Counter from collections module to compute the frequency of characters in the string and then using list comprehension to extract strings having frequency greater than or equal to K.
Python3
from collections import Counter
# initializing list
test_list = ["Geeksforgeeks", "is", "best", "for", "geeks"]
# printing original list
print("The original list is : " + str(test_list))
# initializing characters list
char_list = ['e', 't', 's', 'm', 'n']
# initializing K
K = 2
# using Counter to compute frequency of characters
# and then filtering using list comprehension
res = [ele for ele in test_list if sum(Counter(ele)[ch] for ch in char_list) >= K]
# printing result
print("Filtered Strings : " + str(res))
OutputThe original list is : ['Geeksforgeeks', 'is', 'best', 'for', 'geeks']
Filtered Strings : ['Geeksforgeeks', 'best', 'geeks']
Time Complexity: O(n * m) (m is the length of the longest string and n is the number of strings in the list)
Auxiliary Space: O(n)
Method 4: Using a for loop and a set to keep track of the characters in the character list.
This approach uses a for loop to iterate over the strings in the test_list, and another for loop to iterate over the characters in the char_list. It keeps track of the count of each character in the current string using the count() method, and adds it to a running total. Once the count of characters in the current string is greater than or equal to K, the string is added to the result list using the append() method, and the inner for loop is terminated using the break keyword.
Python3
# initializing list
test_list = ["Geeksforgeeks", "is", "best", "for", "geeks"]
# printing original list
print("The original list is : " + str(test_list))
# initializing characters list
char_list = ['e', 't', 's', 'm', 'n']
# initializing K
K = 2
# using a for loop and a set to filter strings
res = []
for ele in test_list:
count = 0
for ch in char_list:
count += ele.count(ch)
if count >= K:
res.append(ele)
break
# printing result
print("Filtered Strings : " + str(res))
OutputThe original list is : ['Geeksforgeeks', 'is', 'best', 'for', 'geeks']
Filtered Strings : ['Geeksforgeeks', 'best', 'geeks']
Time complexity: O(n*m), where n is the number of strings in the test_list and m is the maximum length of a string in the list.
Auxiliary space: O(1), as we only use a constant amount of additional memory to keep track of the count of characters.
Method 5: use the itertools.product() function
- Import the itertools module.
- Initialize a list called "test_list" with some strings.
- Print the original list using the "print()" function.
- Initialize another list called "char_list" with some characters.
- Initialize a variable "K" with a value of 2.
- Use a list comprehension to filter out the strings from "test_list" that contain any combination of characters in "char_list" of length "K" or greater. This is done using the "itertools.product()" function to generate all possible combinations of length "K" from "char_list" and the "str.find()" method to check if any of these combinations are in the current string being processed in the list comprehension. The filtered strings are stored in a list called "res".
- Print the filtered strings using the "print()" function.
Python3
# import itertools module
import itertools
# initializing list
test_list = ["Geeksforgeeks", "is", "best", "for", "geeks"]
# printing original list
print("The original list is : " + str(test_list))
# initializing characters list
char_list = ['e', 't', 's', 'm', 'n']
# initializing K
K = 2
# using itertools.product() function and str.find() method to filter strings
res = [ele for ele in test_list if any(ele.find(
''.join(combo)) != -1 for combo in itertools.product(char_list, repeat=K))]
# printing result
print("Filtered Strings : " + str(res))
OutputThe original list is : ['Geeksforgeeks', 'is', 'best', 'for', 'geeks']
Filtered Strings : ['Geeksforgeeks', 'best', 'geeks']
Time complexity: O(N*M^K), where N is the length of the test_list, M is the length of the char_list, and K is the length of the combination.
Auxiliary space: O(N).
Method 6: Using regular expressions
- Import the re module to work with regular expressions.
- Initialize an empty list res to store the filtered strings.
- Compile a regular expression pattern using the re.compile() method that matches any combination of characters from char_list of length K.
- Loop through each string s in test_list.
- Use the re.findall() method to find all the matches of the pattern in s. If the length of the resulting list is greater than zero, it means that at least one combination of characters was found in s.
- Append s to res if at least one combination of characters was found in s.
- Return res.
Python3
import itertools
import re
test_list = ["Geeksforgeeks", "is", "best", "for", "geeks"]
char_list = ['e', 't', 's', 'm', 'n']
K = 2
res = []
pattern = re.compile('|'.join(''.join(c) for c in itertools.product(char_list, repeat=K)))
for s in test_list:
if len(pattern.findall(s)) > 0:
res.append(s)
print("Filtered Strings : " + str(res))
OutputFiltered Strings : ['Geeksforgeeks', 'best', 'geeks']
Time complexity: O(nm), where n is the length of test_list and m is the maximum length of a string in test_list.
Auxiliary space: O(n), since we're storing the filtered strings in res.
Similar Reads
Python program to extract characters in given range from a string list
Given a Strings List, extract characters in index range spanning entire Strings list. Input : test_list = ["geeksforgeeks", "is", "best", "for", "geeks"], strt, end = 14, 20 Output : sbest Explanation : Once concatenated, 14 - 20 range is extracted.Input : test_list = ["geeksforgeeks", "is", "best",
4 min read
Python program to check if a string has at least one letter and one number
The task is to verify whether a given string contains both at least one letter (either uppercase or lowercase) and at least one number. For example, if the input string is "Hello123", the program should return True since it contains both letters and numbers. On the other hand, a string like "Hello"
3 min read
Python - Extract String till all occurrence of characters from other string
Given a string, the task is to write a Python program to extract till all characters from other strings are found. Input : test_str = "geeksforgeeks is best for all geeks", check_str = "freak"Output : geeksforgeeks is best for aExplanation : a is last letter in freak to be present in string. The str
11 min read
Python program to Sort a List of Strings by the Number of Unique Characters
Given a list of strings. The task is to sort the list of strings by the number of unique characters. Examples: Input : test_list = ['gfg', 'best', 'for', 'geeks'], Output : ['gfg', 'for', 'best', 'geeks'] Explanation : 2, 3, 4, 4 are unique elements in lists. Input : test_list = ['gfg', 'for', 'geek
6 min read
Python program to find the character position of Kth word from a list of strings
Given a list of strings. The task is to find the index of the character position for the word, which lies at the Kth index in the list of strings. Examples: Input : test_list = ["geekforgeeks", "is", "best", "for", "geeks"], K = 21 Output : 0Explanation : 21st index occurs in "geeks" and point to "g
3 min read
Python - Convert list of strings and characters to list of characters
Sometimes we come forward to the problem in which we receive a list that consists of strings and characters mixed and the task we need to perform is converting that mixed list to a list consisting entirely of characters. Using itertools.chain()itertools.chain() combines multiple lists or iterables i
3 min read
Python program to extract only the numbers from a list which have some specific digits
Given the elements List, extract numbers with specific digits. Input : test_list = [3456, 23, 128, 235, 982], dig_list = [2, 3, 5, 4] Output : [23, 235] Explanation : 2, 3 and 2, 3, 5 are in digit list, hence extracted elements.Input : test_list = [3456, 23, 28, 235, 982], dig_list = [2, 3, 5, 4, 8]
7 min read
Python - Create a string made of the first and last two characters from a given string
To solve the problem, we need to create a new string that combines the first two and the last two characters of a given string. If the input string is too short (less than 2 characters), we should return an empty string. This task is simple and can be achieved using a variety of methods.Using slicin
2 min read
Python program to check if lowercase letters exist in a string
Checking for the presence of lowercase letters involves scanning the string and verifying if at least one character is a lowercase letter (from 'a' to 'z').Python provides simple and efficient ways to solve this problem using built-in string methods and constructs like loops and comprehensions.Using
2 min read
Count the number of characters in a String - Python
The goal here is to count the number of characters in a string, which involves determining the total length of the string. For example, given a string like "GeeksForGeeks", we want to calculate how many characters it contains. Letâs explore different approaches to accomplish this.Using len()len() is
2 min read