📜  Python程序获取字符串构造的最少元素

📅  最后修改于: 2022-05-13 01:54:38.041000             🧑  作者: Mango

Python程序获取字符串构造的最少元素

给定一个字符串,任务是编写一个Python程序来计算从列表元素形成字符串所需的最少元素。

方法:使用 issubset() + set() +组合()

在这里,我们迭代一个字符串列表并形成所有大小的组合,每个组合都被转换为 set 并使用 issubset() 检查是否形成目标字符串,如果找到,则退出循环并记录计数。

Python3
# Python3 code to demonstrate working of 
# Minimum elements for String construction
# Using issubset() + set() + combinations()
from itertools import combinations
  
# initializing list
test_list = ["geek", "ring", "sfor", "ok", "woke"]
  
# printing original list
print("The original list is : " + str(test_list))
  
# initializing target string 
tar_str = "working"
  
res = -1
set_str = set(tar_str)
done = False
for val in range(0, len(test_list) + 1):
      
    # creating combinations
    for sub in combinations(test_list, val):
          
        # contructing sets of each combinations 
        temp_set = set(ele for subl in sub for ele in subl)
          
        # checking if target string has created set as subset
        if set_str.issubset(temp_set):
            res = val
            done = True
            break
    if done:
        break
  
# printing result 
print("The Minimum count elements for string : " + str(res))


输出:

The original list is : ['geek', 'ring', 'sfor', 'ok', 'woke']
The Minimum count elements for string : 2