Python Program To Get Minimum Element For String Construction

PythonServer Side ProgrammingProgramming

When it is required to get the minimum element to construct a string, the ‘set’ operator, the ‘combinations’ method, the ‘issubset’ method and a simple iteration is required.


Below is a demonstration of the same

from itertools import combinations

my_list = ["python", "is", "fun", "to", "learn"]

print("The list is :")

my_target_str = "onis"

my_result = -1
my_set_string = set(my_target_str)
complete_val = False
for value in range(0, len(my_list) + 1):

   for sub in combinations(my_list, value):

      temp_set = set(ele for subl in sub for ele in subl)

      if my_set_string.issubset(temp_set):
         my_result = value
         complete_val = True
   if complete_val:

print("The result is :")


The list is :
['python', 'is', 'fun', 'to', 'learn']
The result is :


  • The required packages are imported into the environment.

  • A list is defined and is displayed on the console.

  • Another string is defined.

  • The string is converted to a list.

  • The list is iterated over, and different combinations of the elements in the list are obtained.

  • The list is iterated over and converted to a set.

  • The ‘issubset’ method is used to check if a certain value belongs to the set.

  • If yes, a variable is assignd ‘True’ value, and breaks out of the loop.

  • If this value is ‘True’ in the end, the result is displayed on the console.

Updated on 14-Sep-2021 10:19:58