Open In App

Python | Check if given string can be formed by concatenating string elements of list

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

Given a string ‘str’ and a list of string elements, write a Python program to check whether given string can be formed by concatenating the string elements of list or not. 

Examples: 

Input : str = 'python'
        lst = ['co', 'de', 'py', 'ks', 'on']
Output : False

Input : str = 'geeks'
        lst = ['for', 'ge', 'abc', 'ks', 'e', 'xyz']
Output : True

Approach #1 : Using itertools.permutations

We can use all the permutations of the given list and then perform join operation on them. If any join result is equal to the given string, return true, otherwise false.  

Python3




# Python3 program to Check if given string can
# be formed by concatenating string elements
# of list
from itertools import permutations
 
def checkList(str, lst):
    for i in range(2, len(lst)+1):
        for perm in permutations(lst, i):
            if ''.join(perm)== str:
                return True
                 
    return False
     
# Driver code
str = 'geeks'
lst = ['for', 'ge', 'abc', 'ks', 'e', 'xyz']
print(checkList(str, lst))


Output: 

True

 

Approach #2 : Python RegEx

Python3




# Python3 program to Check if given string can
# be formed by concatenating string elements
# of list
import re
 
def checkList(str, lst):
 
    r = re.compile("(?:" + "|".join(lst) + ")*$")
    if r.match(str) != None:
        return True
         
    return False
     
# Driver code
str = 'geeks'
lst = ['for', 'ge', 'abc', 'ks', 'e']
print(checkList(str, lst))


Output: 

True

 

Approach#3: Using String.replace() and loop: We iterate over the list element by element and remove that element in string. After all Iteration if string become empty then it can be form by using list of string else it cannot. 

Python3




# Python3 program to Check if given string can
# be formed by concatenating string elements
# of list
 
# Function to check string can be formed using list or not
def checkList(str1, list1):
    # Iterating over list of string
    for i in list1:
        # Replacing the sub-string from string
        str1 = str1.replace(i, "")
        # Checking the emptiness of string
        if str1 == "":
            return True
             
    # Else returning False
    else: return False
     
# Driver code
str = 'geeks'
lst = ['for', 'ge', 'abc', 'e', 'ks', 'xyz']
print(checkList(str, lst))


Output:

True

Approach#4: Using dynamic programming

this approach uses dynamic programming to check if the given string can be formed by concatenating string elements of the list. It initializes a boolean list and checks if any prefix of the string till that index is present in the given list and if the previous index is also True. If it is, it sets the current index to True. It returns the value at the last index of the list.

Algorithm

1. Initialize a boolean list of length n+1 where n is the length of the given string.
2. Set the 0th index to True since an empty string can always be formed.
3. For each index i, starting from 1, check if any prefix of the string till that index is present in the given list and if the previous index is also True.
4. If it is, set the current index to True.
5. If the last index is True, return True else return False.

Python3




def check_concatenation(str, lst):
    n = len(str)
    dp = [False]*(n+1)
    dp[0] = True
    for i in range(1, n+1):
        for j in range(i):
            if dp[j] and str[j:i] in lst:
                dp[i] = True
                break
    return dp[n]
str = 'geeks'
lst = ['for', 'ge', 'abc', 'e', 'ks', 'xyz']
print(check_concatenation(str, lst))


Output

True

Time complexity: O(n^3), where n is the length of the given string.

Auxiliary Space: O(n).

Approach#5: Using the lambda function

In this approach, we will define a lambda function checkList(str, lst) to check if the string ‘str’ can be formed by concatenating the elements of the list ‘lst’.

Algorithm: 
1. For each length i of sub-lists from 2 to length of lst:
    a. Generate all possible permutations of length i using itertools.permutations.
    b. If the concatenated string of any permutation equals the given string ‘str’, return True.
2. Return False if the function has not yet returned True.
3. In the main block, set the string ‘str‘ and the list ‘lst‘.
4. Call the checkList function with ‘str‘ and ‘lst‘ as arguments and print the result.

Python3




from itertools import permutations
 
checkList = lambda s, lst: any(''.join(perm) == s for i in range(2, len(lst) + 1) for perm in permutations(lst, i))
 
# Driver code
s = 'geeks'
lst = ['for', 'ge', 'abc', 'ks', 'e', 'xyz']
print(checkList(s, lst))


Output

True

Time Complexity: O(n^3)

Auxiliary Space: O(n)

METHOD 6:Using recursion

APPROACH:

The program checks if a given string can be formed by concatenating string elements of a list. It does this by recursively checking if each substring of the input string is present in the list. 

ALGORITHM:

1.Define a function is_possible that takes two arguments, string and lst.
2..If string is empty, return True.
3.Loop through lst and check if string starts with any of the words.
4.If string starts with a word, call is_possible with remaining string and lst.
5.If recursive call returns True, return True.
6.If none of the words match, return False.

Python3




def is_possible(string, lst):
    if string == "":
        return True
    for word in lst:
        if string.startswith(word):
            if is_possible(string[len(word):], lst):
                return True
    return False
 
string = 'geeks'
lst = ['for', 'ge', 'abc', 'ks', 'e', 'xyz']
print(is_possible(string, lst)) # True


Output

True

Time Complexity: O(n^m) where n is the length of the string and m is the length of the list.
Auxiliary Space: O(m) where m is the length of the list.



Next Article

Similar Reads

Check if a string can be formed from another string by at most X circular clockwise shifts
Given an integer X and two strings S1 and S2, the task is to check that string S1 can be converted to the string S2 by shifting characters circular clockwise atmost X times. Input: S1 = "abcd", S2 = "dddd", X = 3 Output: Yes Explanation: Given string S1 can be converted to string S2 as- Character "a" - Shift 3 times - "d" Character "b" - Shift 2 ti
7 min read
Python3 Program to Check if a string can be formed from another string by at most X circular clockwise shifts
Given an integer X and two strings S1 and S2, the task is to check that string S1 can be converted to the string S2 by shifting characters circular clockwise atmost X times. Input: S1 = "abcd", S2 = "dddd", X = 3 Output: Yes Explanation: Given string S1 can be converted to string S2 as- Character "a" - Shift 3 times - "d" Character "b" - Shift 2 ti
3 min read
Python Program to create an OTP by squaring and concatenating the odd digits of a number
Given a number n. The task is to create an OTP by squaring and concatenating the odd digits of the number. Examples: Input: 4365188 Output: 9256 Input: 123456 Output: 4163 Explanation: In the First example, the integers at odd places are 3, 5, and 8. So we have to return a 4 digit OTP by squaring the digits. The square of the above digits are 9, 25
2 min read
Python program to check whether number formed by combining all elements of the array is palindrome
Given an array arr[], the task is to combine all the elements in the array sequentially and check if it is a palindrome. Examples: Input: arr[] ={1 , 69 , 54 , 45 , 96 , 1} Output: palindrome Explanation: The number formed by combining all the elements is "1695445961" which is a palindrome Input: arr[] ={2 , 73 , 95 , 59 , 96 , 2} Output: not palin
4 min read
MoviePy – Concatenating multiple Video Files
In this article, we will see how we can concatenate multiple video file clips in MoviePy. MoviePy is a Python module for video editing, which can be used for basic operations on videos and GIF's. In formal language theory and computer programming, string concatenation is the operation of joining character strings end-to-end. For example, the concat
2 min read
How To Add Identifier Column When Concatenating Pandas dataframes?
We generally want to concat two or more dataframes when working with some data. So, when we concat these dataframes we need to actually want to provide an identifier column in order to identify the concatenated dataframes. In this article, we'll see with the help of examples of how we can do this. Example 1: To add an identifier column, we need to
2 min read
Concatenating CSV files using Pandas module
Using pandas we can perform various operations on CSV files such as appending, updating, concatenating, etc. In this article, we are going to concatenate two CSV files using pandas module. Suppose we have one .csv file named Employee.csv which contains some records and it is as below: There is another .csv file named Updated.csv which contains new
3 min read
Python - Check if elements index are equal for list elements
Given two lists and check list, test if for each element in check list, elements occur in similar index in 2 lists. Input : test_list1 = [2, 6, 9, 7, 8], test_list2 = [2, 7, 9, 4, 8], check_list = [9, 8, 7] Output : False Explanation : 7 is at 4th and 2nd place in both list, hence False. Input : test_list1 = [2, 6, 9, 7, 8], test_list2 = [2, 6, 9,
4 min read
Python - Check List elements from Dictionary List
Sometimes, while working with data, we can have a problem in which we need to check for list element presence as a particular key in list of records. This kind of problem can occur in domains in which data are involved like web development and Machine Learning. Lets discuss certain ways in which this task can be solved. Input : test_list = [{'Price
4 min read
Python Check if the List Contains Elements of another List
In Python programming, there can be a case where we have to check whether a list contains elements of Another List or not. In that case, we can follow several approaches for doing so. In this article, we will be discussing several approaches to check whether a list contains elements of another list or not. Python List Contains Elements of another L
2 min read
Practice Tags :
three90RightbarBannerImg