Python – Test for Word construction from character list
Last Updated :
09 May, 2023
Given a List and a String, test if the string can be made from list characters.
Examples:
Input : test_list = ['g', 'g', 'e', 'k', 's', '4', 'g', 'g', 'e', 's', 'e', 'e', '4', 'k'],
test_str = 'geeks4geeks'
Output : True
Explanation : String can be made according to character frequencies.
Input : test_list = ['s', '4', 'g', 'g', 'e', 's', 'e', 'e', '4', 'k'], test_str = 'geeks4geeks'
Output : False
Explanation : String cannot be made according to character frequencies.
Method #1: Using all() + count()
In this, we test for all characters count from the string to be less than the frequency of each character in the list. The frequencies are extracted using the count() function.
Python3
test_list = [ 'g' , 'g' , 'e' , 'k' , 's' , '4' , 'g' ,
'g' , 'e' , 's' , 'e' , 'e' , '4' , 'k' ]
print ( "The original list is : " + str (test_list))
test_str = 'geeks4geeks'
res = all (test_str.count( chr ) < = test_list.count( chr ) for chr in test_str)
print ( "Is word construction possible ? : " + str (res))
|
Output
The original list is : ['g', 'g', 'e', 'k', 's', '4', 'g', 'g', 'e', 's', 'e', 'e', '4', 'k']
Is word construction possible ? : True
Time Complexity: O(n)
Auxiliary Space: O(1)
Method #2 : Using Counter()
In this, we compute frequencies using Counter(), and then perform subtraction of words from list characters. In the case of an empty list, means not possible to form a word.
Python3
from collections import Counter
test_list = [ 'g' , 'g' , 'e' , 'k' , 's' , '4' , 'g' ,
'g' , 'e' , 's' , 'e' , 'e' , '4' , 'k' ]
print ( "The original list is : " + str (test_list))
test_str = 'geeks4geeks'
res = not bool ( dict (Counter(test_str) - Counter(test_list)))
print ( "Is word construction possible ? : " + str (res))
|
Output
The original list is : ['g', 'g', 'e', 'k', 's', '4', 'g', 'g', 'e', 's', 'e', 'e', '4', 'k']
Is word construction possible ? : True
Time Complexity: O(n)
Auxiliary Space: O(1)
Method #3: Using re
- Using the re module to check if all the characters in the test string are present in the test list in a single line.
- The code first concatenates the elements of the test list into a single string. Then, the re.search() function is used to search for a match of the test string with a regular expression pattern that consists of only the characters from the concatenated string.
- If the match is found, the re.search() function returns a Match object, which is truthy, and the result will be True.
- If the match is not found, the function returns None, which is false, and the result will be False.
Python3
import re
test_list = [ 'g' , 'g' , 'e' , 'k' , 's' , '4' ,
'g' , 'g' , 'e' , 's' , 'e' , 'e' , '4' , 'k' ]
test_str = 'geeks4geeks'
result = re.search( "^[" + " ".join(test_list) + " ] + $", test_str) is not None
print ( "Is word construction possible? :" , result)
|
Output
Is word construction possible? : True
Time Complexity: O(n)
Auxiliary Space: O(1)
Method #4: Using a dictionary
- Initialize an empty dictionary named char_freq.
- Iterate through each character in the test_list.
- For each character, if it already exists in the char_freq dictionary, increment its frequency count.
- Otherwise, add it to the dictionary with a frequency of 1.
- Iterate through each character in the test_str.
- For each character, if it exists in the char_freq dictionary and its frequency count is greater than 0, decrement its frequency count. Otherwise, the word cannot be constructed from the test_list.
- If all characters in the test_str have been successfully checked, return True to indicate that the word can be constructed from the test_list. Otherwise, return False.
- The time complexity of this method is O(n), where n is the length of the test_list or test_str. The auxiliary space complexity is also O(n), where n is the number of unique characters in the test_list
Example:
Python3
test_list = [ 'g' , 'g' , 'e' , 'k' , 's' , '4' , 'g' ,
'g' , 'e' , 's' , 'e' , 'e' , '4' , 'k' ]
print ( "The original list is : " + str (test_list))
test_str = 'geeks4geeks'
char_freq = {}
for c in test_list:
if c in char_freq:
char_freq + = 1
else :
char_freq = 1
for c in test_str:
if c in char_freq and char_freq > 0 :
char_freq - = 1
else :
res = False
break
else :
res = True
print ( "Is word construction possible ? : " + str (res))
|
Output
The original list is : ['g', 'g', 'e', 'k', 's', '4', 'g', 'g', 'e', 's', 'e', 'e', '4', 'k']
Is word construction possible ? : True
Time complexity: O(n), where n is the length of the test_list or test_str.
Auxiliary space: O(n), where n is the number of unique characters in the test_list.
Method #5 : Using operator.countOf() method
Approach:
- Remove duplicates from string test_str and store in x using list(),set() methods,set a variable c=0
- Check whether count of elements in test_list is greater than or equal to the count of elements in test_str, if yes increment c by 1(using operator.countOf())
- If c is equal to the length of x then the given string test_str can be formed from test_list, set res to True.
- Else set res to False.
- Print boolean true or false based on whether the word can be made from the input.
Python3
test_list = [ 'g' , 'g' , 'e' , 'k' , 's' , '4' , 'g' ,
'g' , 'e' , 's' , 'e' , 'e' , '4' , 'k' ]
print ( "The original list is : " + str (test_list))
test_str = 'geeks4geeks'
x = list ( set (test_str))
res = False
import operator
c = 0
for i in x:
if (operator.countOf(test_list,i)> = operator.countOf(test_str,i)):
c + = 1
res = c = = len (x)
print ( "Is word construction possible ? : " + str (res))
|
Output
The original list is : ['g', 'g', 'e', 'k', 's', '4', 'g', 'g', 'e', 's', 'e', 'e', '4', 'k']
Is word construction possible ? : True
Time Complexity : O(N) N – length of x
Auxiliary Space: O(1) Since we are using a single variable result.
Similar Reads
Remove words containing list characters - Python
In this article, we will explore various methods to remove words containing list characters in Python. The simplest way to do is by using a loop. Using a LoopIterate over each word in the list and check if it contains any of the characters from remove_chars. If a word contains any of those character
2 min read
Python | Construct string from character frequency tuple
Sometimes, while working with data, we can have a problem in which we need to perform construction of string in a way that we have a list of tuple having character and it's corresponding frequency and we require to construct a new string from that. Let's discuss certain ways in which this task can b
5 min read
Python - Consecutive Repetition of Characters
Sometimes, while working with character lists we can have a problem in which we need to perform consecutive repetition of characters. This can have applications in many domains. Let us discuss certain ways in which this task can be performed. Method #1: Using list comprehension This is one of the
5 min read
Python - Remove Non-English characters Strings from List
Given a List of Strings, perform removal of all Strings with non-english characters. Input : test_list = ['Good| ????', '??Geeks???'] Output : [] Explanation : Both contain non-English characters Input : test_list = ["Gfg", "Best"] Output : ["Gfg", "Best"] Explanation : Both are valid English words.
8 min read
Python Program to find if a character is vowel or Consonant
Given a character, check if it is vowel or consonant. Vowels are 'a', 'e', 'i', 'o' and 'u'. All other characters ('b', 'c', 'd', 'f' ....) are consonants. Examples: Input : x = 'c'Output : ConsonantInput : x = 'u'Output : VowelRecommended: Please try your approach on {IDE} first, before moving on t
5 min read
Python - Fill list characters in String
Given String and list, construct a string with only list values filled. Input : test_str = "geeksforgeeks", fill_list = ['g', 's', 'f', k] Output : g__ksf__g__ks Explanation : All occurrences are filled in their position of g, s, f and k. Input : test_str = "geeksforgeeks", fill_list = ['g', 's'] Ou
9 min read
Python - Group list by first character of string
Sometimes, we have a use case in which we need to perform the grouping of strings by various factors, like first letter or any other factor. These types of problems are typical to database queries and hence can occur in web development while programming. This article focuses on one such grouping by
7 min read
Split String into List of characters in Python
We are given a string and our task is to split this string into a list of its individual characters, this can happen when we want to analyze or manipulate each character separately. For example, if we have a string like this: 'gfg' then the output will be ['g', 'f', 'g']. Using ListThe simplest way
2 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 | Convert string List to Nested Character List
Sometimes, while working with Python, we can have a problem in which we need to perform interconversion of data. In this article we discuss converting String list to Nested Character list split by comma. Let's discuss certain ways in which this task can be performed. Method #1 : Using list comprehen
7 min read