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:
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course
Input : str = 'python'
lst = ['co', 'de', 'py', 'ks', 'on']
Output : False
Input : str = 'geeks'
lst = ['for', 'ge', 'abc', 'ks', 'e', 'xyz']
Output : TrueApproach #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 listfrom itertools import permutationsdef 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 codestr = 'geeks'lst = ['for', 'ge', 'abc', 'ks', 'e', 'xyz']print(checkList(str, lst)) |
True
Approach #2 : Python RegEx
Python3
# Python3 program to Check if given string can# be formed by concatenating string elements# of listimport redef checkList(str, lst): r = re.compile("(?:" + "|".join(lst) + ")*$") if r.match(str) != None: return True return False # Driver codestr = 'geeks'lst = ['for', 'ge', 'abc', 'ks', 'e']print(checkList(str, lst)) |
True


