如何查找字符串的所有可能的子序列?
例如:s = 'abc'
所有可能的子序列为:
{a} {b} {c} {ab} {ac} {bc} {abc}
答案 0 :(得分:0)
最惯用的方式可能是:
from itertools import compress, product
s = 'abc'
L = [tuple(compress(s, selector)) for selector in product([True, False], repeat=len(s))]
print(L)
# [('a', 'b', 'c'), ('a', 'b'), ('a', 'c'), ('a',), ('b', 'c'), ('b',), ('c',), ()]
如果您希望输出包含字符串而不是元组,请将tuple(...)
替换为''.join(...)
L = [''.join(compress(s, selector)) for selector in product([True, False], repeat=len(s))]
print(L)
# ['abc', 'ab', 'ac', 'a', 'bc', 'b', 'c', '']