python字符串子集的所有组合

was*_*256 7 python subset

我需要字符串子集的所有组合.此外,长度为1的子集后面只能跟一个长度> 1的子集.例如,对于字符串4824,结果应为:

 [ [4, 824], [4, 82, 4], [48, 24], [482, 4], [4824] ]
Run Code Online (Sandbox Code Playgroud)

到目前为止,我设法检索所有可能的子集:

    length = len(number)
    ss = []
    for i in xrange(length):
        for j in xrange(i,length):
            ss.append(number[i:j + 1])
Run Code Online (Sandbox Code Playgroud)

这给了我:

  ['4', '48', '482', '4824', '8', '82', '824', '2', '24', '4']
Run Code Online (Sandbox Code Playgroud)

但我现在不知道如何将它们结合起来.

tob*_*s_k 8

首先,编写一个函数来生成字符串的所有分区:

def partitions(s):
    if s:
        for i in range(1, len(s) + 1):
            for p in partitions(s[i:]):
                yield [s[:i]] + p
    else:
        yield []
Run Code Online (Sandbox Code Playgroud)

这将迭代所有可能的第一个段(一个字符,两个字符等),并将这些段与字符串的相应剩余部分的所有分区组合在一起.

>>> list(partitions("4824"))
[['4', '8', '2', '4'], ['4', '8', '24'], ['4', '82', '4'], ['4', '824'], ['48', '2', '4'], ['48', '24'], ['482', '4'], ['4824']]
Run Code Online (Sandbox Code Playgroud)

现在,您可以只过滤那些符合您条件的那些,即那些没有两个长度为1的连续子串的那些.

>>> [p for p in partitions("4824") if not any(len(x) == len(y) == 1 for x, y in zip(p, p[1:]))]
[['4', '82', '4'], ['4', '824'], ['48', '24'], ['482', '4'], ['4824']]
Run Code Online (Sandbox Code Playgroud)

这里zip(p, p[1:])是迭代所有连续项对的常用方法.


更新:实际上,将约束直接合并到partition函数中也不是那么难.只需跟踪最后一段并相应地设置最小长度.

def partitions(s, minLength=1):
    if len(s) >= minLength:
        for i in range(minLength, len(s) + 1):
            for p in partitions(s[i:], 1 if i > 1 else 2):
                yield [s[:i]] + p
    elif not s:
        yield []
Run Code Online (Sandbox Code Playgroud)

演示:

>>> print list(partitions("4824"))
[['4', '82', '4'], ['4', '824'], ['48', '24'], ['482', '4'], ['4824']]
Run Code Online (Sandbox Code Playgroud)