Python - 从字符串保留最小的子集
给定一组字符串,任务是写一个Python程序从套被发现字符串的最小可能子集保留的字符串。
Input : test_set = {‘cbabca’, ‘cba’, ‘bdb’, ‘bdbab’, ‘abcx’}
Output : {‘bdb’, ‘abcx’, ‘cba’}
Explanation : bdbab is removed as bdb ( smaller subset ) is retained.
Input : test_set = {‘cbabca’, ‘cba’, ‘bdbab’, ‘abcx’}
Output : {‘bdbab’, ‘abcx’, ‘cba’}
Explanation : cbabca is removed as cba ( smaller subset ) is retained.
方法:使用sorted() + any() +字符串切片
在此,我们通过对子字符串集进行排序来执行获取最小子字符串的任务,并使用 any() 测试是否有任何子集与作为小于当前字符串的结果提取的字符串存在的字符串子字符串匹配,以及字符串的子集。
Python3
# Python3 code to demonstrate working of
# Retain smallest subsets from string
# Using sorted() + any() + string slicing
# initializing strings set
test_set = {'cbabca', 'cba', 'bdb', 'bdbab', 'abcx'}
# printing original string
print("The original set is : " + str(test_set))
res = set()
for st_r in sorted(test_set, key=len):
# getting smallest set and checking for already
# present smaller set for subset
if not any(st_r[idx: idx + y + 1] in res
for idx in range(len(st_r))
for y in range(len(st_r) - idx)):
res.add(st_r)
# printing result
print("Required extracted strings : " + str(res))
输出:
The original set is : {'cba', 'abcx', 'bdb', 'bdbab', 'cbabca'}
Required extracted strings : {'abcx', 'cba', 'bdb'}