Change language

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 

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

Python | Check if a given string can be formed by concatenating string list items String Variables: Questions

Shop

Best laptop for Fortnite

$

Best laptop for Excel

$

Best laptop for Solidworks

$

Best laptop for Roblox

$

Best computer for crypto mining

$

Best laptop for Sims 4

$

Best laptop for Zoom

$499

Best laptop for Minecraft

$590

Latest questions

NUMPYNUMPY

psycopg2: insert multiple rows with one query

12 answers

NUMPYNUMPY

How to convert Nonetype to int or string?

12 answers

NUMPYNUMPY

How to specify multiple return types using type-hints

12 answers

NUMPYNUMPY

Javascript Error: IPython is not defined in JupyterLab

12 answers

News

Wiki

Python OpenCV | cv2.putText () method

numpy.arctan2 () in Python

Python | os.path.realpath () method

Python OpenCV | cv2.circle () method

Python OpenCV cv2.cvtColor () method

Python - Move item to the end of the list

time.perf_counter () function in Python

Check if one list is a subset of another in Python

Python os.path.join () method