我需要字符串子集的所有组合.另外,长度为1的子集之后只能是长度> 1的子集.例如对于字符串4824,结果应该是:
[ [4,824],[4,82,4],[48,24],[482,[4824] ]
到目前为止,我设法检索所有可能的子集:
length = len(number)
ss = []
for i in xrange(length):
for j in xrange(i,length):
ss.append(number[i:j + 1])
这给了我:
['4','48','482','4824','8','82','824','2','24','4']
但我现在不知道如何将它们结合起来.
解决方法
首先,编写一个函数来生成字符串的所有分区:
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 []
这将迭代所有可能的第一个段(一个字符,两个字符等),并将这些段与字符串的相应剩余部分的所有分区组合在一起.
>>> list(partitions("4824"))
[['4','4'],['4','24'],'824'],['48',['482',['4824']]
现在,您可以只过滤那些符合您条件的条件,即那些没有两个连续长度为1的子串的条件.
>>> [p for p in partitions("4824") if not any(len(x) == len(y) == 1 for x,y in zip(p,p[1:]))]
[['4',['4824']]
这里,zip(p,p [1:])是迭代所有连续项对的常用方法.
更新:实际上,将约束直接合并到分区函数中也不是那么难.只需跟踪最后一段并相应地设置最小长度.
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 []
演示:
>>> print list(partitions("4824"))
[['4',['4824']]