Python | Check if a given string can be formed by concatenating string list items



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.permuations

We can use all permutations from the given list and then join with them. If any join result is the given string, return true, otherwise false.

# Python3 program to check if a given string can
# be formed by concatenating inline elements
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

< code class = "functions"> str = `geeks`

lst = [ `for` , `ge` , `abc` , ` ks` , `e` , ` xyz` ]

print (checkList ( str , lst))

Exit:

 True 

Approach # 2: Python RegEx

# Python3 program for pro checks if a given string can
# be formed by combining string elements
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))

Exit:

 True