Python | Check if given string can be formed by concatenating string elements of list
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 is 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
Please Login to comment...