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

PythonServer Side ProgrammingProgramming

We sometimes need to check if a required string can be formed from many number of strings that are present in a list. It also should not matter in what order the strings are present in the list which have to be joined to get the required string.

With permutations

From itertools we can use the permutations function which will give us the possible combinations of the strings in the list in various order. As soon as a given combination matches the required string, we conclude that the string can be formed.

Example

 Live Demo

from itertools import permutations

chk_str = 'balloon'
Alist = ['fly','on', 'o', 'hot', 'ball', 'air']

def findstring(strchk, biglist):
   for i in range(2, len(biglist) + 1):
      for perm in permutations(biglist, i):
         if ''.join(perm) == strchk:
         return True
   return False

# Using the function
if(findstring(chk_str,Alist)):
   print("String can be formed.")
else:
   print("String can not be formed.")

Output

Running the above code gives us the following result −

String can be formed.

With Regular Expressions

The re module provides the compile function which will create the possible strings by specifying the regular expression pattern. Then it will be compared with the string to be checked. If the result is not none then we can conclude the string can be formed.

Example

 Live Demo

import re

chk_str = 'balloon'
Alist = ['fly','on', 'o', 'hot', 'ball', 'air']

def findstring(strchk, biglist):
   r = re.compile("(?:" + "|".join(biglist) + ")*$")
   if r.match(strchk) != None:
      return True
   return False

# Using the function
if(findstring(chk_str,Alist)):
   print("String can be formed.")
else:
   print("String can not be formed.")

Output

Running the above code gives us the following result −

String can be formed.
raja
Published on 13-May-2020 17:59:44
Advertisements