我试图获取字符串的每个子集,却不知道该怎么做。如果有人可以帮助我,那就太好了。

>>> string('ab')
    a, b
>>> string('abc')
    a, b, c, ab, ac, bc,
>>> string('abcd')
    a, b, c, d, ab, bc, cd, da, abc, bcd, cda, dab,


这些都必须在列表中,并且字符串中可能有n个字符。该程序应返回所有可以形成的字符串子集。

最佳答案

您可以使用itertools.combinations并像这样列出理解

from itertools import combinations
def myStrings(s):
    return ["".join(item) for i in range(1,len(s)) for item in combinations(s,i)]

print myStrings('ab')
print myStrings('abc')
print myStrings('abcd')


输出量

['a', 'b']
['a', 'b', 'c', 'ab', 'ac', 'bc']
['a', 'b', 'c', 'd', 'ab', 'ac', 'ad', 'bc', 'bd', 'cd', 'abc', 'abd', 'acd', 'bcd']

关于python - 字符串的子集,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/20161706/

10-12 17:30
查看更多