Python 如何遍历1和!的所有子组合s

Python 如何遍历1和!的所有子组合s,python,string,combinations,Python,String,Combinations,假设我有一个看起来像1000101的字符串 我想迭代所有可能的插入方法!其中1是: 1000101 100010! 1000!01 1000!0! !000101 !00010! !000!01 !000!0! 可扩展到任意字符串和任意数量的1。递归结构是,我可以生成s[1:]的所有子ombo,然后为每个组合插入到前面!如果s[0]为1,则插入s[0] 发电机的一种方法: def possibilities(s): if

假设我有一个看起来像1000101的字符串

我想迭代所有可能的插入方法!其中1是:

    1000101
    100010!
    1000!01
    1000!0!
    !000101
    !00010!
    !000!01
    !000!0!

可扩展到任意字符串和任意数量的1。递归结构是,我可以生成s[1:]的所有子ombo,然后为每个组合插入到前面!如果s[0]为1,则插入s[0]


发电机的一种方法:

def possibilities(s):
    if not s:
        yield ""
    else:
        for s_next in possibilities(s[1:]):
            yield "".join([s[0], s_next])
            if s[0] == '1':
                yield "".join(['!', s_next])

print list(possibilities("1000101"))
输出:

['1000101', '!000101', '1000!01', '!000!01', '100010!', '!00010!', '1000!0!', '!000!0!']
与往常一样,为了救援:

>>> from itertools import product
>>> s = "10000101"
>>> all_poss = product(*(['1', '!'] if c == '1' else [c] for c in s))
>>> for x in all_poss:
...     print(''.join(x))
...     
10000101
1000010!
10000!01
10000!0!
!0000101
!000010!
!0000!01
!0000!0!
因为我们在这里使用的是一个字符串,所以我们甚至可以不使用它

product(*('1!' if c == '1' else c for c in s))

如果需要。

计算一个限制的个数,然后使用二进制计数器进行选择。@Deduplicator我确实尝试过,但无法将两者融合在一起,所以我放弃了它
product(*('1!' if c == '1' else c for c in s))