
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Check If String Can Be Formed by Concatenating List Elements in Python
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
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
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.